from requests.packages.urllib3.exceptions import InsecureRequestWarning

# !usr/bin/env python
# -*- coding:utf-8 -*-
"""
@author: lenovo by amidoufu
@file: amidoufu.py
@time: 2020/05/06
@function: 
"""
import requests
import json
import time
import os
import webbrowser
import re
import emoji
import ssl
import fileinput
import sys
import random
import threading
import pygame
import configparser
import tkinter.messagebox
from tkinter import *
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver import ActionChains
from requests.packages.urllib3.exceptions import InsecureRequestWarning
from PIL import Image
import numpy as np
import sklearn
from  sklearn import cluster
import cv2
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

ssl._create_default_https_context = ssl._create_unverified_context

INFO = {
    "name": "奥利给丶快手批量下载助手",
    "author": "阿米豆腐丶",
    "repository": "最初版本oGsLP提供,最初源码下载地址:www.github.com/oGsLP/kuaishou-crawler",
    "version": "0.2",
    "publishDate": "20-05-06"
}

PROFILE_URL = "https://live.kuaishou.com/profile/"
DATA_URL = "https://live.kuaishou.com/m_graphql"
WORK_URL = "https://v.kuaishou.com/fw/photo/"




__param_did = ""

__headers_web = {
    'accept': '*/*',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7',
    'Connection': 'keep-alive',
    'Content-Type': 'application/json',
    'Host': 'live.kuaishou.com',
    'Origin': 'https://live.kuaishou.com',
    'Sec-Fetch-Mode': 'cors',
    'Sec-Fetch-Site': 'same-origin',
    # User-Agent/Cookie 根据自己的电脑修改
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36',
    'Cookie': ''
}
__headers_mobile = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',#'*/*',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'Connection': 'keep-alive',#'close',
    'Host': 'v.kuaishou.com',
    'Sec-Fetch-Dest': 'document',
    'Sec-Fetch-Mode': 'navigate',
    'Sec-Fetch-Site': 'none',
    'Upgrade-Insecure-Requests': '1',
    'User-Agent': '',
    'Cookie': ''
}
__headers_Requests_web = {
    'accept': '*/*',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7',
    'Connection': 'keep-alive',
    'Host': 'v.kuaishou.com',
    'Upgrade-Insecure-Requests': '1',
    # User-Agent/Cookie 根据自己的电脑修改
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36',
    'Cookie': ''
}
# User-Agent': 'Mozilla/5.0 (Linux; U; Android 8.1.0; zh-cn; BLA-AL00 Build/HUAWEIBLA-AL00) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.132 MQQBrowser/8.9 Mobile Safari/537.36

class QJ:
    exists = 0
    stop = False
    userid_cook = ""
    sid_cook = ""
    current_uid = ""
    video_num = 0
    uid_jici = 0
    yzm_num = 0
    ua_list_ = ""
    bak_uid = ""
    find_url1_last = ""
    find_url2_last = ""
    find_url3_last = ""
    cookie_mobile = ""
    duanlian = ""
    duanlian_list = []
    uid_list_num = 0
    zhuangtaima = ""
    dkkm = ""
    jiqima = ""
    jiance_uid = 0
    uid_list_zongshu_bak = 0
    __doufu_list_jiance = []
    doufu_list__ = []
    bakuid = ""
    bakname = ""
    cookie1 = ""
    cookie2 = ""
    cookie3 = ""
    cookie4 = ""
    cookie5 = ""
    mdl = 0
    max_x = 0
    work_beifen = 0
    work_beifen2 = 0


ua_list = ['Mozilla/5.0 (BB10; Touch) AppleWebKit/537.10+ (KHTML, like Gecko) Version/10.0.9.2372 Mobile Safari/537.10+','Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30','Mozilla/5.0 (Linux; U; Android 4.1; en-us; GT-N7100 Build/JRO03C) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30','Mozilla/5.0 (Linux; U; Android 4.0; en-us; GT-I9300 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30','Mozilla/5.0 (Linux; U; Android 4.4.2; en-us; LGMS323 Build/KOT49I.MS32310c) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/83.0.4103.97 Mobile Safari/537.36','Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 550) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Mobile Safari/537.36 Edge/14.14263','Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 950) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Mobile Safari/537.36 Edge/14.14263','Mozilla/5.0 (Linux; Android 6.0.1; Moto G (4)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Mobile Safari/537.36','Mozilla/5.0 (Linux; Android 6.0.1; Nexus 10 Build/MOB31T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36','Mozilla/5.0 (PlayBook; U; RIM Tablet OS 2.1.0; en-US) AppleWebKit/536.2+ (KHTML like Gecko) Version/7.2.1.0 Safari/536.2+','Mozilla/5.0 (Linux; Android 4.4.2; Nexus 4 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Mobile Safari/537.36','Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Mobile Safari/537.36','Mozilla/5.0 (Linux; Android 8.0.0; Nexus 5X Build/OPR4.170623.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Mobile Safari/537.36','Mozilla/5.0 (Linux; Android 7.1.1; Nexus 6 Build/N6F26U) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Mobile Safari/537.36','Mozilla/5.0 (Linux; Android 8.0.0; Nexus 6P Build/OPP3.170518.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Mobile Safari/537.36','Mozilla/5.0 (Linux; Android 6.0.1; Nexus 7 Build/MOB30X) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36','Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 520)','Mozilla/5.0 (MeeGo; NokiaN9) AppleWebKit/534.13 (KHTML, like Gecko) NokiaBrowser/8.5.0 Mobile Safari/534.13','Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1','Mozilla/5.0 (iPhone; CPU iPhone OS 7_1_2 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Version/7.0 Mobile/11D257 Safari/9537.53','Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Mobile Safari/537.36','Mozilla/5.0 (Linux; Android 8.0; Pixel 2 Build/OPD3.170816.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Mobile Safari/537.36','Mozilla/5.0 (Linux; Android 8.0.0; Pixel 2 XL Build/OPD1.170816.004) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Mobile Safari/537.36','Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1','Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1','Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1','Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1','Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1','Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1']
exists = 0
click_access = 0
xiladaili = ""
__doufu_list = []

__date_cache = ""
__date_pic_count = 0

def __init__():
    if QJ.userid_cook != "":
        thread_it(doufu,)
    else:
        thread_it(__intro,)

def set_did(did, did2, did3, did4, did5):
    __param_did = did
    # __param_did1 = did1
    __param_did2 = did2
    __param_did3 = did3
    __param_did4 = did4
    __param_did5 = did5
    # __param_did3 = did3
    options = webdriver.ChromeOptions()
    options.add_argument(
        'User-Agent=' + QJ.ua_list_)
    driver = webdriver.Chrome(executable_path="Google Chrome/chromedriver.exe", chrome_options=options)
    driver.get(QJ.duanlian)
    # driver.implicitly_wait(30)
    file = '提示音.wav'  # 文件名是完整路径名
    # divs = driver.find_elements_by_tag_name('div')
    # for div in divs:
    #     if '继续观看内容' in div.text:
    #         divs1 = driver.find_elements_by_tag_name('div')
    #         for div1 in divs1:
    #             if '继续观看' in div1.text:
    #                 div1.click()
    #     else:
    #         break

    time.sleep(3)
    iframes = driver.find_elements_by_tag_name("iframe")
    if iframes != []:
        time.sleep(1)
        driver.refresh()
        time.sleep(1)
        iframes = driver.find_elements_by_tag_name("iframe")
    while iframes != []:
        # driver.implicitly_wait(30)
        pygame.mixer.init()  # 初始化音频
        track = pygame.mixer.music.load(file)  # 载入音乐文件
        pygame.mixer.music.play()  # 开始播放
        time.sleep(3)
        iframes = driver.find_elements_by_tag_name("iframe")
        if iframes != []:
            text.insert(END, "出现验证码弹窗请等待自动验证或者自动验证失败后在手动验证")
            text.update()
            text.see(END)
            iframe = driver.find_elements_by_tag_name("iframe")[0]
            driver.switch_to.default_content()
            driver.switch_to.frame(iframe)
            bgtu = driver.find_element_by_xpath('/html/body/div/div/div[1]/img[1]')
            bgtu_link = bgtu.get_attribute("src")
            #r = requests.get(bgtu_link, verify=False)
            while True:  # 一直循环，知道访问站点成功
                try:
                    # 以下except都是用来捕获当requests请求出现异常时，
                    # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
                    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
                    r = requests.get(bgtu_link, verify=False)
                    r.raise_for_status()
                    # res = requests.get(w_url, headers=__headers_mobile, verify=False)
                    # res.raise_for_status()
                    break
                except requests.exceptions.HTTPError:
                    text.insert(END, "HTTPError, 等待5秒后再次下载!!!")
                    text.update()
                    text.see(END)
                    time.sleep(5)
                except requests.exceptions.ConnectionError:
                    text.insert(END, "ConnectionError, 等待5秒后再次下载!!!")
                    text.update()
                    text.see(END)
                    time.sleep(5)
                except requests.exceptions.ChunkedEncodingError:
                    text.insert(END, "ChunkedEncodingError, 等待5秒后再次下载!!!")
                    text.update()
                    text.see(END)
                    time.sleep(5)
                except:
                    text.insert(END, "Unfortunitely -- An Unknow Error Happened, 等待60秒后程序重新运行!!!")
                    text.update()
                    text.see(END)
                    time.sleep(60)
                    restart_program()
            dir = "./"
            # if not os.path.exists(dir):
            #     os.makedirs(dir)
            bjtu_pic = dir + "2.png"
            with open(bjtu_pic, "wb") as f:
                f.write(r.content)
            slidertu = driver.find_element_by_xpath('/html/body/div/div/div[1]/img[2]')
            slidertu_link = slidertu.get_attribute("src")
            #r = requests.get(slidertu_link, verify=False)
            while True:  # 一直循环，知道访问站点成功
                try:
                    # 以下except都是用来捕获当requests请求出现异常时，
                    # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
                    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
                    r = requests.get(slidertu_link, verify=False)
                    r.raise_for_status()
                    # res = requests.get(w_url, headers=__headers_mobile, verify=False)
                    # res.raise_for_status()
                    break
                except requests.exceptions.HTTPError:
                    text.insert(END, "HTTPError, 等待5秒后再次下载!!!")
                    text.update()
                    text.see(END)
                    time.sleep(5)
                except requests.exceptions.ConnectionError:
                    text.insert(END, "ConnectionError, 等待5秒后再次下载!!!")
                    text.update()
                    text.see(END)
                    time.sleep(5)
                except requests.exceptions.ChunkedEncodingError:
                    text.insert(END, "ChunkedEncodingError, 等待5秒后再次下载!!!")
                    text.update()
                    text.see(END)
                    time.sleep(5)
                except:
                    text.insert(END, "Unfortunitely -- An Unknow Error Happened, 等待60秒后程序重新运行!!!")
                    text.update()
                    text.see(END)
                    time.sleep(60)
                    restart_program()
            dir = "./"
            # if not os.path.exists(dir):
            #     os.makedirs(dir)
            slider_pic = dir + "1.png"
            with open(slider_pic, "wb") as f:
                f.write(r.content)
            image_pyramid()
            image_contrast()
            huakuai = driver.find_element_by_xpath('/html/body/div/div/div[2]/div[2]/div/i')
            time.sleep(1)
            # move_to_gap(huakuai, get_track(340))
            ActionChains(driver).click_and_hold(huakuai).perform()
            for x in get_track(QJ.max_x * 4 - 25):
                ActionChains(driver).move_by_offset(xoffset=x, yoffset=0).perform()
            time.sleep(0.5)
            ActionChains(driver).release().perform()
            time.sleep(5)
            driver.switch_to.default_content()
            time.sleep(1)
            #driver.refresh()
        pygame.mixer.music.stop()  # 停止播放
        iframes = driver.find_elements_by_tag_name("iframe")
        if iframes == []:
            pygame.mixer.music.stop()  # 停止播放
            break
        else:
            driver.refresh()
    cookie5 = [item['name'] + '=' + item['value'] for item in driver.get_cookies()]
    cookie3 = [item['name'] for item in driver.get_cookies()]
    cookie4 = [item['value'] for item in driver.get_cookies()]
    sep = "; "
    QJ.cookie_mobile = sep.join(cookie5)
    for cookie3_jici in range(len(cookie3)):
        if cookie3[cookie3_jici] == "sid":
            QJ.sid_cook = cookie4[cookie3_jici]
            break
    url_ = driver.current_url
    find_url_1 = 'fid=(.*?)&photoId='
    find_url_2 = '&shareId=(.*?)&userId='
    find_url_3 = '&shareType=(.*?)&timestamp='
    find_url1 = re.findall(find_url_1, url_)
    find_url2 = re.findall(find_url_2, url_)
    find_url3 = re.findall(find_url_3, url_)
    QJ.find_url1_last = find_url1[0]
    QJ.find_url2_last = find_url2[0]
    QJ.find_url3_last = find_url3[0]
    driver.close()
    __headers_web[
        'Cookie'] = 'did=' + did + '; userId=' + did5 + '; kuaishou.live.web_st=' + did2 + '; kuaishou.live.web_ph=' + did3 + '; kuaishou.live.bfb1s=' + did4
    __headers_mobile['Cookie'] = QJ.cookie_mobile#'did=' + did + ';userId=' + did5 + ';didv=' + str(int(time.time()) * 1000) + ';sid=' + QJ.sid_cook
    # text.insert(END,"初始化成功...")
    # text.update()
    # text.see(END)
    text.insert(END, "用户电脑cookie的值：" + 'did=' + did + '; userId=' + did5 + '; kuaishou.live.web_st=' + did2 + '; kuaishou.live.web_ph=' + did3 + '; kuaishou.live.bfb1s=' + did4)
    text.update()
    text.see(END)
    text.insert(END, "")
    text.update()
    text.see(END)
    text.insert(END, "用户手机cookie的值：" + QJ.cookie_mobile)
    text.update()
    text.see(END)
    if click_access != 1:
        thread_it(doufu, )
    else:
        thread_it(one_click_access2, )
    # __headers_web['Cookie'] = 'did=' + did + ';kuaishou.live.web_ph=' + did1 + ';kuaishou.live.web_st=' + did2 + ';kuaishou.live.bfb1s=' + did3 +';didv=' + str(int(time.time())*1000) + ';userId='
    # __headers_mobile['Cookie'] = 'did=' + did + ';kuaishou.live.web_ph=' + did1 + ';kuaishou.live.web_st=' + did2 + ';kuaishou.live.bfb1s=' + did3 +';didv=' + str(int(time.time())*1000) + ';userId='




def doufu():
    latetime = int(entry.get())
    text.insert(END, "")
    text.update()
    text.see(END)
    text.insert(END,"延时时间:" + str(latetime))
    text.update()
    text.see(END)
    text.insert(END, "")
    text.update()
    text.see(END)
    text.insert(END,"准备开始爬取，共有%d个用户..." % len(QJ.doufu_list__))
    text.update()
    text.see(END)
    time.sleep(3)
    #读取class全局变量
    QJ.uid_list_zongshu_bak = len(QJ.doufu_list__)
    QJ.uid_jici = 0
    for uid in QJ.doufu_list__:
        if QJ.current_uid != "0":
            if uid != QJ.current_uid:
                QJ.uid_jici = QJ.uid_jici + 1
                if QJ.jiance_uid == 1:
                    uid_list_num = QJ.uid_jici + 1
                if QJ.uid_jici == len(QJ.doufu_list__):
                    QJ.uid_jici = 0
                    QJ.video_num = 0
                    break
            else:
                break
        else:
            QJ.uid_jici = 0
            QJ.video_num = 0
            break
    for uid_list_num in range(QJ.uid_jici,len(QJ.doufu_list__)):
        uid = QJ.doufu_list__[uid_list_num]
        QJ.current_uid = uid
        QJ.uid_list_num = uid_list_num
        save_config_jb2()
        QJ.bakuid = uid
        __date_cache = ""
        __date_count = 0
        if "kuaishou" in uid:  # kuaishouapp.com
            if "/profile" in uid:
                if "?fid" in uid:
                    recovery3 = uid
                    recovery4 = re.sub(r'[?]+', "", recovery3)
                    waitreplace_uid = '/profile/(.*?)fid'
                    uid1 = re.findall(waitreplace_uid, recovery4)
                    text.insert(END, "Short chain1:" + uid + "丨Uid:" + uid1[0] + "丨当前第" + str(uid_list_num + 1) + "个用户")
                    text.update()
                    text.see(END)
                    time.sleep(3)
                    QJ.bak_uid =uid1[0]
                    __doufu_user(uid1[0], latetime)
                else:
                    recovery3 = uid
                    recovery_list = recovery3.split("/")
                    uid1 = recovery_list[4]
                    text.insert(END, "Short chain1:" + uid + "丨Uid:" + uid1 + "丨当前第" + str(uid_list_num + 1) + "个用户")
                    text.update()
                    text.see(END)
                    time.sleep(3)
                    QJ.bak_uid = uid1
                    __doufu_user(uid1, latetime)
            else:
                r = requests.get(uid, headers=__headers_Requests_web)
                # print(r.history)
                reditList = r.history  # 可以看出获取的是一个地址序列
                # print(f'获取重定向的历史记录：{reditList}')
                # print(f'获取第一次重定向的headers头部信息：{reditList[0].headers}')
                # print(f'获取重定向最终的url：{reditList[len(reditList) - 1].headers["location"]}')
                recovery1 = reditList
                recovery2 = reditList[0].headers
                recovery3 = reditList[len(reditList) - 1].headers["location"]
                if "?fid" in recovery3:
                    recovery4 = re.sub(r'[?]+', "", recovery3)
                    waitreplace_uid = '/profile/(.*?)fid'
                    uid1 = re.findall(waitreplace_uid, recovery4)
                    text.insert(END, "Short chain1:" + uid + "丨Uid:" + uid1[0] + "丨当前第" + str(uid_list_num + 1) + "个用户")
                    text.update()
                    text.see(END)
                    time.sleep(3)
                    QJ.bak_uid = uid1[0]
                    __doufu_user(uid1[0], latetime)
                else:
                    recovery_list = recovery3.split("/")
                    uid1 = recovery_list[4]
                    text.insert(END, "Short chain2:" + uid + "丨Uid:" + uid1 + "丨当前第" + str(uid_list_num + 1) + "个用户")
                    text.update()
                    text.see(END)
                    QJ.bak_uid = uid1
                    __doufu_user(uid1, latetime)
        else:
            text.insert(END, "丨Uid:" + uid + "丨当前第" + str(uid_list_num + 1) + "个用户")
            text.update()
            text.see(END)
            QJ.bak_uid = uid
            __doufu_user(uid, latetime)


def add_to_list(uid):
    QJ.doufu_list__.append(uid)

def add_to_list2(uid):
    QJ.__doufu_list_jiance.append(uid)

def chongxinduqu_uid():
    QJ.__doufu_list_jiance = []
    p_path2 = "uid.txt"
    with open(p_path2, "r") as f2:
        for line2 in f2:
            if line2[0] != "#":
                QJ.__doufu_list_jiance.append(line2.strip())
    if len(QJ.__doufu_list_jiance) != QJ.uid_list_zongshu_bak:
        QJ.jiance_uid = 1
        QJ.doufu_list__ = []
        new_uid_list = tkinter.messagebox.askokcancel('提示', 'uid.txt有更新,请问是否重启程序后重新获取uid列表!!!')
        if new_uid_list == True:
            restart_program()



def __doufu_user(uid, latetime):
    if uid.isdigit():
        uid = __switch_id(uid)

    if var9.get() == 1:
        text.insert(END, "现在使用的老版本参数(最多500个作品,无等待时间)")
        text.update()
        text.see(END)
        huoquzuopinshu = 99999
    else:
        text.insert(END, "现在使用的新版本参数(获取全部作品，每次200个作品,每次需等待30秒)")
        text.update()
        text.see(END)
        huoquzuopinshu = 200
    page = 1
    payload = {"operationName": "privateFeedsQuery",
               "variables": {"principalId": uid, "pcursor": "", "count": huoquzuopinshu},
               "query": "query privateFeedsQuery($principalId: String, $pcursor: String, $count: Int) {\n  privateFeeds(principalId: $principalId, pcursor: $pcursor, count: $count) {\n    pcursor\n    list {\n      id\n      thumbnailUrl\n      poster\n      workType\n      type\n      useVideoPlayer\n      imgUrls\n      imgSizes\n      magicFace\n      musicName\n      caption\n      location\n      liked\n      onlyFollowerCanComment\n      relativeHeight\n      timestamp\n      width\n      height\n      counts {\n        displayView\n        displayLike\n        displayComment\n        __typename\n      }\n      user {\n        id\n        eid\n        name\n        avatar\n        __typename\n      }\n      expTag\n      __typename\n    }\n    __typename\n  }\n}\n"}

    #"query": "query privateFeedsQuery($principalId: String, $pcursor: String, $count: Int) {\n  privateFeeds(principalId: $principalId, pcursor: $pcursor, count: $count) {\n    pcursor\n    list {\n      id\n      thumbnailUrl\n      poster\n      workType\n      type\n      useVideoPlayer\n      imgUrls\n      imgSizes\n      magicFace\n      musicName\n      caption\n      location\n      liked\n      onlyFollowerCanComment\n      relativeHeight\n      timestamp\n      width\n      height\n      counts {\n        displayView\n        displayLike\n        displayComment\n        __typename\n      }\n      user {\n        id\n        eid\n        name\n        avatar\n        __typename\n      }\n      expTag\n      __typename\n    }\n    __typename\n  }\n}\n"}
    # payload = {"operationName": "privateFeedsQuery",
    #            "variables":{"principalId":uid,"pcursor":"","count":99999},
    #            "query": "query privateFeedsQuery($principalId: String, $pcursor: String, $count: Int) {\n  privateFeeds(principalId: $principalId, pcursor: $pcursor, count: $count) {\n    pcursor\n    list {\n      id\n      thumbnailUrl\n      poster\n      workType\n      type\n      useVideoPlayer\n      imgUrls\n      imgSizes\n      magicFace\n      musicName\n      caption\n      location\n      liked\n      onlyFollowerCanComment\n      relativeHeight\n      timestamp\n      width\n      height\n      counts {\n        displayView\n        displayLike\n        displayComment\n        __typename\n      }\n      user {\n        id\n        eid\n        name\n        avatar\n        __typename\n      }\n      expTag\n      __typename\n    }\n    __typename\n  }\n}\n"}
    #res = requests.post(DATA_URL, headers=__headers_web, verify=False, json=payload)
    while True:  # 一直循环，知道访问站点成功
        try:
            # 以下except都是用来捕获当requests请求出现异常时，
            # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
            requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
            res = requests.post(DATA_URL, headers=__headers_web, verify=False, json=payload)
            res.raise_for_status()
            break
        except requests.exceptions.HTTPError:
            text.insert(END, "HTTPError, 等待5秒后再次下载!!!")
            text.update()
            text.see(END)
            time.sleep(5)
        except requests.exceptions.ConnectionError:
            text.insert(END, "ConnectionError, 等待5秒后再次下载!!!")
            text.update()
            text.see(END)
            time.sleep(5)
        except requests.exceptions.ChunkedEncodingError:
            text.insert(END, "ChunkedEncodingError, 等待5秒后再次下载!!!")
            text.update()
            text.see(END)
            time.sleep(5)
        except:
            text.insert(END, "Unfortunitely -- An Unknow Error Happened, 等待60秒后程序重新运行!!!")
            text.update()
            text.see(END)
            time.sleep(60)
            restart_program()

    works = json.loads(res.content.decode(encoding='utf-8', errors='strict'))['data']['privateFeeds']['list']
    pcursor = json.loads(res.content.decode(encoding='utf-8', errors='strict'))['data']['privateFeeds']['pcursor']

    if var10.get() == 1:
        if len(works) == 500:
            text.insert(END, "判断作品超过500个,30秒后自动切换为获取全部作品版本参数")
            text.update()
            text.see(END)
            text.insert(END, "获取全部作品版本参数(获取全部作品，每次200个作品,每次需等待30秒)")
            text.update()
            text.see(END)
            time.sleep(30)
            huoquzuopinshu = 200
            page = 1
            payload = {"operationName": "privateFeedsQuery",
                       "variables": {"principalId": uid, "pcursor": "", "count": huoquzuopinshu},
                       "query": "query privateFeedsQuery($principalId: String, $pcursor: String, $count: Int) {\n  privateFeeds(principalId: $principalId, pcursor: $pcursor, count: $count) {\n    pcursor\n    list {\n      id\n      thumbnailUrl\n      poster\n      workType\n      type\n      useVideoPlayer\n      imgUrls\n      imgSizes\n      magicFace\n      musicName\n      caption\n      location\n      liked\n      onlyFollowerCanComment\n      relativeHeight\n      timestamp\n      width\n      height\n      counts {\n        displayView\n        displayLike\n        displayComment\n        __typename\n      }\n      user {\n        id\n        eid\n        name\n        avatar\n        __typename\n      }\n      expTag\n      __typename\n    }\n    __typename\n  }\n}\n"}

            # "query": "query privateFeedsQuery($principalId: String, $pcursor: String, $count: Int) {\n  privateFeeds(principalId: $principalId, pcursor: $pcursor, count: $count) {\n    pcursor\n    list {\n      id\n      thumbnailUrl\n      poster\n      workType\n      type\n      useVideoPlayer\n      imgUrls\n      imgSizes\n      magicFace\n      musicName\n      caption\n      location\n      liked\n      onlyFollowerCanComment\n      relativeHeight\n      timestamp\n      width\n      height\n      counts {\n        displayView\n        displayLike\n        displayComment\n        __typename\n      }\n      user {\n        id\n        eid\n        name\n        avatar\n        __typename\n      }\n      expTag\n      __typename\n    }\n    __typename\n  }\n}\n"}
            # payload = {"operationName": "privateFeedsQuery",
            #            "variables":{"principalId":uid,"pcursor":"","count":99999},
            #            "query": "query privateFeedsQuery($principalId: String, $pcursor: String, $count: Int) {\n  privateFeeds(principalId: $principalId, pcursor: $pcursor, count: $count) {\n    pcursor\n    list {\n      id\n      thumbnailUrl\n      poster\n      workType\n      type\n      useVideoPlayer\n      imgUrls\n      imgSizes\n      magicFace\n      musicName\n      caption\n      location\n      liked\n      onlyFollowerCanComment\n      relativeHeight\n      timestamp\n      width\n      height\n      counts {\n        displayView\n        displayLike\n        displayComment\n        __typename\n      }\n      user {\n        id\n        eid\n        name\n        avatar\n        __typename\n      }\n      expTag\n      __typename\n    }\n    __typename\n  }\n}\n"}
            # res = requests.post(DATA_URL, headers=__headers_web, verify=False, json=payload)
            while True:  # 一直循环，知道访问站点成功
                try:
                    # 以下except都是用来捕获当requests请求出现异常时，
                    # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
                    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
                    res = requests.post(DATA_URL, headers=__headers_web, verify=False, json=payload)
                    res.raise_for_status()
                    break
                except requests.exceptions.HTTPError:
                    text.insert(END, "HTTPError, 等待5秒后再次下载!!!")
                    text.update()
                    text.see(END)
                    time.sleep(5)
                except requests.exceptions.ConnectionError:
                    text.insert(END, "ConnectionError, 等待5秒后再次下载!!!")
                    text.update()
                    text.see(END)
                    time.sleep(5)
                except requests.exceptions.ChunkedEncodingError:
                    text.insert(END, "ChunkedEncodingError, 等待5秒后再次下载!!!")
                    text.update()
                    text.see(END)
                    time.sleep(5)
                except:
                    text.insert(END, "Unfortunitely -- An Unknow Error Happened, 等待60秒后程序重新运行!!!")
                    text.update()
                    text.see(END)
                    time.sleep(60)
                    restart_program()

            works = json.loads(res.content.decode(encoding='utf-8', errors='strict'))['data']['privateFeeds']['list']
            pcursor = json.loads(res.content.decode(encoding='utf-8', errors='strict'))['data']['privateFeeds'][
                'pcursor']


    if huoquzuopinshu == 200:
        QJ.work_beifen = len(works)
        text.insert(END, "正在获取第" + str(page) + "页视频丨共" + str(len(works)) + "个视频")
        text.update()
        text.see(END)
        time.sleep(30)



    if works != []:
        while pcursor != "no_more":
            page += 1
            payload = {"operationName": "privateFeedsQuery",
                       "variables": {"principalId": uid, "pcursor": pcursor, "count": huoquzuopinshu},
                       "query": "query privateFeedsQuery($principalId: String, $pcursor: String, $count: Int) {\n  privateFeeds(principalId: $principalId, pcursor: $pcursor, count: $count) {\n    pcursor\n    list {\n      id\n      thumbnailUrl\n      poster\n      workType\n      type\n      useVideoPlayer\n      imgUrls\n      imgSizes\n      magicFace\n      musicName\n      caption\n      location\n      liked\n      onlyFollowerCanComment\n      relativeHeight\n      timestamp\n      width\n      height\n      counts {\n        displayView\n        displayLike\n        displayComment\n        __typename\n      }\n      user {\n        id\n        eid\n        name\n        avatar\n        __typename\n      }\n      expTag\n      __typename\n    }\n    __typename\n  }\n}\n"}

            #"query": "query privateFeedsQuery($principalId: String, $pcursor: String, $count: Int) {\n  privateFeeds(principalId: $principalId, pcursor: $pcursor, count: $count) {\n    pcursor\n    list {\n      id\n      thumbnailUrl\n      poster\n      workType\n      type\n      useVideoPlayer\n      imgUrls\n      imgSizes\n      magicFace\n      musicName\n      caption\n      location\n      liked\n      onlyFollowerCanComment\n      relativeHeight\n      timestamp\n      width\n      height\n      counts {\n        displayView\n        displayLike\n        displayComment\n        __typename\n      }\n      user {\n        id\n        eid\n        name\n        avatar\n        __typename\n      }\n      expTag\n      __typename\n    }\n    __typename\n  }\n}\n"}
            # "query": "query privateFeedsQuery($principalId: String, $pcursor: String, $count: Int) {\n  privateFeeds(principalId: $principalId, pcursor: $pcursor, count: $count) {\n    pcursor\n    list {\n      id\n      thumbnailUrl\n      poster\n      workType\n      type\n      useVideoPlayer\n      imgUrls\n      imgSizes\n      magicFace\n      musicName\n      caption\n      location\n      liked\n      onlyFollowerCanComment\n      relativeHeight\n      timestamp\n      width\n      height\n      counts {\n        displayView\n        displayLike\n        displayComment\n        __typename\n      }\n      user {\n        id\n        eid\n        name\n        avatar\n        __typename\n      }\n      expTag\n      __typename\n    }\n    __typename\n  }\n}\n"}
            # payload = {"operationName": "privateFeedsQuery",
            #            "variables":{"principalId":uid,"pcursor":"","count":99999},
            #            "query": "query privateFeedsQuery($principalId: String, $pcursor: String, $count: Int) {\n  privateFeeds(principalId: $principalId, pcursor: $pcursor, count: $count) {\n    pcursor\n    list {\n      id\n      thumbnailUrl\n      poster\n      workType\n      type\n      useVideoPlayer\n      imgUrls\n      imgSizes\n      magicFace\n      musicName\n      caption\n      location\n      liked\n      onlyFollowerCanComment\n      relativeHeight\n      timestamp\n      width\n      height\n      counts {\n        displayView\n        displayLike\n        displayComment\n        __typename\n      }\n      user {\n        id\n        eid\n        name\n        avatar\n        __typename\n      }\n      expTag\n      __typename\n    }\n    __typename\n  }\n}\n"}
            # res = requests.post(DATA_URL, headers=__headers_web, verify=False, json=payload)
            while True:  # 一直循环，知道访问站点成功
                try:
                    # 以下except都是用来捕获当requests请求出现异常时，
                    # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
                    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
                    res = requests.post(DATA_URL, headers=__headers_web, verify=False, json=payload)
                    res.raise_for_status()
                    break
                except requests.exceptions.HTTPError:
                    text.insert(END, "HTTPError, 等待5秒后再次下载!!!")
                    text.update()
                    text.see(END)
                    time.sleep(5)
                except requests.exceptions.ConnectionError:
                    text.insert(END, "ConnectionError, 等待5秒后再次下载!!!")
                    text.update()
                    text.see(END)
                    time.sleep(5)
                except requests.exceptions.ChunkedEncodingError:
                    text.insert(END, "ChunkedEncodingError, 等待5秒后再次下载!!!")
                    text.update()
                    text.see(END)
                    time.sleep(5)
                except:
                    text.insert(END, "Unfortunitely -- An Unknow Error Happened, 等待60秒后程序重新运行!!!")
                    text.update()
                    text.see(END)
                    time.sleep(60)
                    restart_program()
            pcursor = json.loads(res.content.decode(encoding='utf-8', errors='strict'))['data']['privateFeeds'][
                'pcursor']
            works = works + json.loads(res.content.decode(encoding='utf-8', errors='strict'))['data']['privateFeeds'][
                'list']
            # if page == 2:
            #     QJ.work_beifen2 = works
            # elif page == 3:
            #     QJ.work_beifen2 = works
            # elif page == 4:
            #     QJ.work_beifen2 = works
            # elif page == 5:
            #     QJ.work_beifen2 = works
            # elif page == 6:
            #     QJ.work_beifen2 = works
            # elif page == 7:
            #     QJ.work_beifen2 = works
            # elif page == 8:
            #     QJ.work_beifen2 = works
            # elif page == 9:
            #     QJ.work_beifen2 = works
            # elif page == 10:
            #     QJ.work_beifen2 = works
            # elif page == 11:
            #     QJ.work_beifen2 = works
            # elif page == 12:
            #     QJ.work_beifen2 = works
            # elif page == 13:
            #     QJ.work_beifen2 = works
            # elif page == 14:
            #     QJ.work_beifen2 = works
            # elif page == 15:
            #     QJ.work_beifen2 = works
            # elif page == 16:
            #     QJ.work_beifen2 = works
            # elif page == 17:
            #     QJ.work_beifen2 = works
            # elif page == 18:
            #     QJ.work_beifen2 = works
            # elif page == 19:
            #     QJ.work_beifen2 = works
            # elif page == 20:
            #     QJ.work_beifen2 = works
            # elif page == 21:
            #     QJ.work_beifen2 = works
            # elif page == 22:
            #     QJ.work_beifen2 = works
            # elif page == 23:
            #     QJ.work_beifen2 = works
            # elif page == 24:
            #     QJ.work_beifen2 = works
            # elif page == 25:
            #     QJ.work_beifen2 = works
            # elif page == 26:
            #     QJ.work_beifen2 = works
            # elif page == 27:
            #     QJ.work_beifen2 = works
            # elif page == 28:
            #     QJ.work_beifen2 = works
            # elif page == 29:
            #     QJ.work_beifen2 = works
            # elif page == 30:
            #     QJ.work_beifen2 = works
            # elif page == 31:
            #     QJ.work_beifen2 = works
            # elif page == 32:
            #     QJ.work_beifen2 = works
            # elif page == 33:
            #     QJ.work_beifen2 = works
            # elif page == 34:
            #     QJ.work_beifen2 = works
            # elif page == 35:
            #     QJ.work_beifen2 = works
            # elif page == 36:
            #     QJ.work_beifen2 = works
            # elif page == 37:
            #     QJ.work_beifen2 = works
            # elif page == 38:
            #     QJ.work_beifen2 = works
            # elif page == 39:
            #     QJ.work_beifen2 = works
            # elif page == 40:
            #     QJ.work_beifen2 = works
            text.insert(END, "正在获取第" + str(page) + "页视频丨共" + str(len(works)) + "个视频")
            text.update()
            text.see(END)
            if huoquzuopinshu == 200:
                time.sleep(30)
            if len(works) == QJ.work_beifen:
                text.insert(END, "数据获取异常3秒后重启软件!!!")
                text.update()
                text.see(END)
                time.sleep(3)
                restart_program()

            if len(works) == QJ.work_beifen2:
                text.insert(END, "数据获取异常3秒后重启软件!!!")
                text.update()
                text.see(END)
                time.sleep(3)
                restart_program()
            # if page == 40:
            #     if len(works) == QJ.work_beifen:
            #         text.insert(END, "数据获取异常3秒后重启软件!!!")
            #         text.update()
            #         text.see(END)
            #         time.sleep(3)
            #         restart_program()
            #     if len(works) == QJ.work_beifen2:
            #         text.insert(END, "数据获取异常3秒后重启软件!!!")
            #         text.update()
            #         text.see(END)
            #         time.sleep(3)
            #         restart_program()
            QJ.work_beifen2 = len(works)

        QJ.work_beifen = 0
        QJ.work_beifen2 = 0
        text.insert(END, "视频获取完成,共" + str(len(works)) + "个视频")
        text.update()
        text.see(END)
        if not os.path.exists("./快手data"):
            os.makedirs("./快手data")

        # 这两行代码将response写入json供分析
        # with open("data/" + uid + ".json", "w") as fp:
        #     fp.write(json.dumps(works, indent=2))

        # 防止该用户在直播，第一个作品默认为直播，导致获取信息为NoneType
        if works[0]['id'] is None:
            works.pop(0)

        data_uid_list_dir = "快手data/"
        data_uid_list = os.listdir(data_uid_list_dir)

        uid_data_shifoucunzai = False
        for data_uid_jici in range(len(data_uid_list)):
            if uid in data_uid_list[data_uid_jici]:
                bingo = data_uid_jici
                uid_data_shifoucunzai = True
                break

        name2 = re.sub(r'[\\/:*?"<>|\r\n]+', "", works[0]['user']['name'])
        emoji_str = emoji.demojize(name2)
        name = re.sub(r':(.*?):', '', emoji_str).strip()
        QJ.bakname = name
        if uid_data_shifoucunzai == True:
            dir = "快手data/" + data_uid_list[bingo] + "/"
            text.insert(END, "开始爬取用户 " + name + "，uid文件夹已存在,保存在目录丨" + dir)
            text.update()
            text.see(END)
            text.insert(END, " 共有" + str(len(works)) + "个作品")
            text.update()
            text.see(END)
            text.insert(END, "")
            text.update()
            text.see(END)
            time.sleep(1)
        else:
            dir = "快手data/" + name + "(" + uid + ")/"
            if not os.path.exists(dir):
                os.makedirs(dir)
            text.insert(END, "开始爬取用户 " + name + "，uid文件夹不存在,已创建目录丨" + dir)
            text.update()
            text.see(END)
            text.insert(END, " 共有" + str(len(works)) + "个作品")
            text.update()
            text.see(END)
            text.insert(END, "")
            text.update()
            text.see(END)
            time.sleep(1)

        # name = re.sub(r'[\\/:*?"<>|\r\n]+', "", works[0]['user']['name'])
        # dir = "快手data/" + name + "(" + uid + ")/"
        # # print(len(works))
        # if not os.path.exists(dir):
        #     os.makedirs(dir)

        # if not os.path.exists(dir + ".list"):
        # print("")

        # #print("开始爬取用户 " + name + "，保存在目录 " + dir)
        # text.insert(END,"开始爬取用户 " + name + "，保存在目录 " + dir)
        # text.update()
        # text.see(END)
        # #print(" 共有" + str(len(works)) + "个作品")
        # text.insert(END," 共有" + str(len(works)) + "个作品")
        # text.update()
        # text.see(END)
        # #print("")
        # text.insert(END,"")
        # text.update()
        # text.see(END)
        # time.sleep(1)

        if not os.path.exists(dir + "图集/"):
            photos = 0
        else:
            photos = len(
                [lists for lists in os.listdir(dir + "图集/") if os.path.isdir(os.path.join(dir + "图集/", lists))])

        if not os.path.exists(dir + "视频/"):
            videos = 0
        else:
            videos = len(
                [lists for lists in os.listdir(dir + "视频/") if os.path.isfile(os.path.join(dir + "视频/", lists))])

        allnumber = photos + videos
        text.insert(END,"丨用户:" + name + "丨" )
        text.update()
        text.see(END)
        text.insert(END, "丨当前电脑共有作品数:" + str(allnumber) + "个丨视频:" + str(videos) + "个丨图集:" + str(photos) + "个丨")
        text.update()
        text.see(END)
        text.insert(END,"" )
        text.update()
        text.see(END)
        time.sleep(1)

        if QJ.video_num != 0:
            lum_num = QJ.video_num
            text.insert(END, "上次记录:" + "Uid or Short chain丨" + QJ.bakuid + "丨第丨" + str(
                QJ.uid_list_num + 1) + "丨个用户" + "丨第丨" + str(lum_num + 1) + "丨个视频")
            text.update()
            text.see(END)
            allnumber = 0
            text.insert(END, "")
            text.update()
            text.see(END)
        else:
            text.insert(END, "新的开始:" + "Uid or Short chain丨" + QJ.bakuid + "丨第丨" + str(
                QJ.uid_list_num + 1) + "丨个用户" + "丨第丨0丨个视频")
            text.update()
            text.see(END)
            lum_num = 0
            allnumber = 0
            text.insert(END, "")
            text.update()
            text.see(END)

        for j in range(lum_num, len(works)):
            chongxinduqu_uid()
            QJ.video_num = j
            save_config_jb2()
            if QJ.stop == True:
                text.insert(END, "成功跳过当前用户...")
                text.update()
                text.see(END)
                break
            __doufu_work(uid, dir, works[j], j + 1)
            if not os.path.exists(dir + "图集/"):
                photos = 0
            else:
                photos = len([lists for lists in os.listdir(dir + "图集/") if
                              os.path.isdir(os.path.join(dir + "图集/", lists))])

            if not os.path.exists(dir + "视频/"):
                videos = 0
            else:
                videos = len([lists for lists in os.listdir(dir + "视频/") if
                              os.path.isfile(os.path.join(dir + "视频/", lists))])

            allnumber = photos + videos
            text.insert(END, "丨用户:" + name + "丨" + "UID:" + uid + "丨第" + str(QJ.uid_list_num + 1) + "个用户丨")
            text.update()
            text.see(END)
            text.insert(END, "丨下载信息如下:丨")
            text.update()
            text.see(END)
            text.insert(END, "丨总下载数:" + str(len(works)) + "个丨" + "当前下载数:" + str(j + 1) + "个丨" + "等待下载数:" + str(
                len(works) - j - 1) + "个丨")
            text.update()
            text.see(END)
            text.insert(END, "丨当前电脑共有作品数:" + str(allnumber) + "个丨视频:" + str(videos) + "个丨图集:" + str(photos) + "个丨")
            text.update()
            text.see(END)
            text.insert(END, "")
            text.update()
            text.see(END)
            if var.get() == 1:
                if QJ.exists == int(entry2.get()):
                    text.insert(END, "正在自动跳过当前用户...")
                    text.update()
                    text.see(END)
                    break

            time.sleep(int(latetime))
            text.insert(END, "")
            text.update()
            text.see(END)


            if not os.path.exists(dir + "图集/"):
                photos = 0
            else:
                photos = len(
                    [lists for lists in os.listdir(dir + "图集/") if os.path.isdir(os.path.join(dir + "图集/", lists))])

            if not os.path.exists(dir + "视频/"):
                videos = 0
            else:
                videos = len([lists for lists in os.listdir(dir + "视频/") if
                              os.path.isfile(os.path.join(dir + "视频/", lists))])

        allnumber = photos + videos
        text.insert(END, "")
        text.update()
        text.see(END)
        text.insert(END, "丨用户:" + name + "丨")
        text.update()
        text.see(END)
        text.insert(END, "丨当前电脑共有作品数:" + str(allnumber) + "个丨视频:" + str(videos) + "个丨图集:" + str(photos) + "个丨")
        text.update()
        text.see(END)
        text.insert(END, "")
        text.update()
        text.see(END)
        text.insert(END, "用户 " + name + "视频爬取完成!")
        text.update()
        text.see(END)

        text.insert(END, "")
        text.update()
        text.see(END)
        config = configparser.ConfigParser()
        config.read('.\\config.ini')
        if config.has_section('基本设置') == False:
            config.add_section('基本设置')

        config.set('基本设置', '没有作品重启计次', str(0))

        o = open('.\\config.ini', 'w')
        config.write(o)
        o.close()  # 不要忘记关闭
        time.sleep(1)
        text.insert(END, "等待10秒执行下一个")
        text.update()
        text.see(END)
        QJ.video_num = 0
        save_config_jb2()
        text.insert(END, "等待9秒执行下一个")
        text.update()
        text.see(END)
        time.sleep(1)
        text.insert(END, "等待8秒执行下一个")
        text.update()
        text.see(END)
        time.sleep(1)
        text.insert(END, "等待7秒执行下一个")
        text.update()
        text.see(END)
        time.sleep(1)
        text.insert(END, "等待6秒执行下一个")
        text.update()
        text.see(END)
        time.sleep(1)
        text.insert(END, "等待5秒执行下一个")
        text.update()
        text.see(END)
        time.sleep(1)
        text.insert(END, "等待4秒执行下一个")
        text.update()
        text.see(END)
        time.sleep(1)
        text.insert(END, "等待3秒执行下一个")
        text.update()
        text.see(END)
        time.sleep(1)
        text.insert(END, "等待2秒执行下一个")
        text.update()
        text.see(END)
        time.sleep(1)
        text.insert(END, "等待1秒执行下一个")
        text.update()
        text.see(END)
        QJ.stop = False
        time.sleep(1)
        text.insert(END, "")
        text.update()
        text.see(END)
        QJ.exists = 0
    else:
        uid_zhuangtai_url = requests.get("https://live.kuaishou.com/profile/" + uid, headers=__headers_web)
        uid_zhuangtai = uid_zhuangtai_url.text
        if "隐私用户" in uid_zhuangtai:
            text.insert(END, "隐私用户自动跳过!!!")
            text.update()
            text.see(END)
            meiyouzuopin_text = open("没有作品.txt", "a+")
            text.insert(END, "正在写入没有作品.txt中,请稍等...")
            text.update()
            text.see(END)
            meiyouzuopin_text.write(str(uid) + "---隐私用户" + "\n")
            meiyouzuopin_text.close()
        elif "该用户因违反社区规定，账号封禁" in uid_zhuangtai:
            text.insert(END, "账号封禁自动跳过!!!")
            text.update()
            text.see(END)
            meiyouzuopin_text = open("没有作品.txt", "a+")
            text.insert(END, "正在写入没有作品.txt中,请稍等...")
            text.update()
            text.see(END)
            meiyouzuopin_text.write(str(uid) + "---封号用户" + "\n")
            meiyouzuopin_text.close()
        elif "该链接指向页面不存在" in uid_zhuangtai:
            text.insert(END, "页面不存在自动跳过!!!")
            text.update()
            text.see(END)
            meiyouzuopin_text = open("没有作品.txt", "a+")
            text.insert(END, "正在写入没有作品.txt中,请稍等...")
            text.update()
            text.see(END)
            meiyouzuopin_text.write(str(uid) + "---链接指向不存在用户" + "\n")
            meiyouzuopin_text.close()
        elif "没有作品" in uid_zhuangtai:
            payload = {"operationName": "sensitiveUserInfoQuery",
                       "variables": {"principalId": uid},
                       "query": "query sensitiveUserInfoQuery($principalId: String) {\n  sensitiveUserInfo(principalId: $principalId) {\n    kwaiId\n    originUserId\n    constellation\n    cityName\n    counts {\n      fan\n      follow\n      photo\n      liked\n      open\n      playback\n      private\n      __typename\n    }\n    __typename\n  }\n}\n"}
                       #"query": "query sensitiveUserInfoQuery($principalId: String) {\n  sensitiveUserInfo(principalId: $principalId) {\n    kwaiId\n    originUserId\n    constellation\n    cityName\n    counts {\n      fan\n      follow\n      photo\n      liked\n      open\n      playback\n      private\n      __typename\n    }\n    __typename\n  }\n}\n"}
            # payload = {"operationName": "privateFeedsQuery",
            #            "variables":{"principalId":uid,"pcursor":"","count":99999},
            #            "query": "query privateFeedsQuery($principalId: String, $pcursor: String, $count: Int) {\n  privateFeeds(principalId: $principalId, pcursor: $pcursor, count: $count) {\n    pcursor\n    list {\n      id\n      thumbnailUrl\n      poster\n      workType\n      type\n      useVideoPlayer\n      imgUrls\n      imgSizes\n      magicFace\n      musicName\n      caption\n      location\n      liked\n      onlyFollowerCanComment\n      relativeHeight\n      timestamp\n      width\n      height\n      counts {\n        displayView\n        displayLike\n        displayComment\n        __typename\n      }\n      user {\n        id\n        eid\n        name\n        avatar\n        __typename\n      }\n      expTag\n      __typename\n    }\n    __typename\n  }\n}\n"}
            # res = requests.post(DATA_URL, headers=__headers_web, verify=False, json=payload)
            while True:  # 一直循环，知道访问站点成功
                try:
                    # 以下except都是用来捕获当requests请求出现异常时，
                    # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
                    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
                    res = requests.post(DATA_URL, headers=__headers_web, verify=False, json=payload)
                    res.raise_for_status()
                    break
                except requests.exceptions.HTTPError:
                    text.insert(END, "HTTPError, 等待5秒后再次下载!!!")
                    text.update()
                    text.see(END)
                    time.sleep(5)
                except requests.exceptions.ConnectionError:
                    text.insert(END, "ConnectionError, 等待5秒后再次下载!!!")
                    text.update()
                    text.see(END)
                    time.sleep(5)
                except requests.exceptions.ChunkedEncodingError:
                    text.insert(END, "ChunkedEncodingError, 等待5秒后再次下载!!!")
                    text.update()
                    text.see(END)
                    time.sleep(5)
                except:
                    text.insert(END, "Unfortunitely -- An Unknow Error Happened, 等待60秒后程序重新运行!!!")
                    text.update()
                    text.see(END)
                    time.sleep(60)
                    restart_program()
            if "photo" in res.text:
                zuopinshu = int(json.loads(res.content.decode(encoding='utf-8', errors='strict'))['data']['sensitiveUserInfo']['counts']['photo'])
            else:
                zuopinshu = 1
            if zuopinshu == 0:
                text.insert(END, "真·没有作品自动跳过!!!")
                text.update()
                text.see(END)
                meiyouzuopin_text = open("没有作品.txt", "a+")
                text.insert(END, "正在写入没有作品.txt中,请稍等...")
                text.update()
                text.see(END)
                meiyouzuopin_text.write(str(uid) + "---真·没有作品用户" + "\n")
                meiyouzuopin_text.close()
            else:
                config = configparser.ConfigParser()
                config.read('.\\config.ini')
                meiyouzuopin_jici = config.getint('基本设置', '没有作品重启计次')
                meiyouzuopin_chongqishijian = config.getint('基本设置', '没有作品重启时间')
                meiyouzuopin_zuidacishu = config.getint('基本设置', '没有作品最大次数')
                if meiyouzuopin_jici < meiyouzuopin_zuidacishu:
                    meiyouzuopin_jici += 1
                    text.insert(END, "可能出现反爬,60秒后自动重启软件并且重新尝试获取列表,5次后自动跳过!!!")
                    text.update()
                    text.see(END)
                    text.insert(END, "当前重启:" + str(meiyouzuopin_jici) + "次")
                    text.update()
                    text.see(END)
                    config = configparser.ConfigParser()
                    config.read('.\\config.ini')
                    if config.has_section('基本设置') == False:
                        config.add_section('基本设置')

                    config.set('基本设置', '没有作品重启计次', str(meiyouzuopin_jici))

                    o = open('.\\config.ini', 'w')
                    config.write(o)
                    o.close()  # 不要忘记关闭

                    config = configparser.ConfigParser()
                    config.read('.\\config.ini')
                    if config.has_section('cookie') == False:
                        config.add_section('cookie')

                    config.set('cookie', 'did', "")
                    config.set('cookie', 'kuaishou.live.web_st', "")
                    config.set('cookie', 'kuaishou.live.web_ph', "")
                    config.set('cookie', 'kuaishou.live.bfb1s', "")
                    config.set('cookie', 'userId', "")

                    o = open('.\\config.ini', 'w')
                    config.write(o)
                    o.close()  # 不要忘
                    time.sleep(meiyouzuopin_chongqishijian)
                    restart_program()
                if meiyouzuopin_jici == meiyouzuopin_zuidacishu:
                    text.insert(END, "已重启"+ str(meiyouzuopin_zuidacishu) + "次,不知道啥原因·没有作品自动跳过!!!")
                    text.update()
                    text.see(END)
                    config = configparser.ConfigParser()
                    config.read('.\\config.ini')
                    if config.has_section('基本设置') == False:
                        config.add_section('基本设置')

                    config.set('基本设置', '没有作品重启计次', str(0))

                    o = open('.\\config.ini', 'w')
                    config.write(o)
                    o.close()  # 不要忘记关闭
                    meiyouzuopin_text = open("没有作品.txt", "a+")
                    text.insert(END, "正在写入没有作品.txt中,请稍等...")
                    text.update()
                    text.see(END)
                    meiyouzuopin_text.write(str(uid) + "---假·没有作品用户" + "\n")
                    meiyouzuopin_text.close()
                # print("在这1")
                # text.insert(END, "可能出现反爬,60秒后自动重启软件并且重新尝试获取列表!!!")
                # text.update()
                # text.see(END)
                # time.sleep(60)
                # config = configparser.ConfigParser()
                # config.read('.\\config.ini')
                # if config.has_section('cookie') == False:
                #     config.add_section('cookie')
                #
                # config.set('cookie', 'did', "")
                # config.set('cookie', 'kuaishou.live.web_st', "")
                # config.set('cookie', 'kuaishou.live.web_ph', "")
                # config.set('cookie', 'kuaishou.live.bfb1s', "")
                # config.set('cookie', 'userId', "")
                #
                # o = open('.\\config.ini', 'w')
                # config.write(o)
                # o.close()  # 不要忘
                # restart_program()

        else:
            # print("在这2")
            text.insert(END, "可能出现反爬,60秒后自动重启软件并且重新尝试获取列表!!!")
            text.update()
            text.see(END)
            config = configparser.ConfigParser()
            config.read('.\\config.ini')
            if config.has_section('cookie') == False:
                config.add_section('cookie')

            config.set('cookie', 'did', "")
            config.set('cookie', 'kuaishou.live.web_st', "")
            config.set('cookie', 'kuaishou.live.web_ph', "")
            config.set('cookie', 'kuaishou.live.bfb1s', "")
            config.set('cookie', 'userId', "")

            o = open('.\\config.ini', 'w')
            config.write(o)
            o.close()  # 不要忘
            time.sleep(60)
            restart_program()

    # lines = [l for l in open("uid.txt", "r") if l.find(uid, 0, 8) != 0]
    # fd = open("uid_log.txt", "w")
    # fd.writelines(lines)
    # fd.close()


    # with open("a.txt", "r+") as f:
    #     p = re.compile("gmail|aol|yahoo")
    #     lines = [line for line in f.readlines() if p.search(line) is None]
    #     f.seek(0)
    #     f.truncate(0)
    #     f.writelines(lines)

    # list = []
    # matchPattern = re.compile(uid)
    # f_path = r'uid.txt'
    # with open(f_path)as f:
    #     while 1:
    #         line = f.readline()
    #         if not line:
    #             break
    #         elif matchPattern.search(line):
    #             pass
    #         else:
    #             list.append(line)
    #     f.close()
    #     f = open('uid_log.txt', 'w')
    #     for i in list:
    #         f.write(i)
    #     f.close()

    '''
    快手分为五种类型的作品，在作品里面表现为workType属性
     * 其中两种图集: `vertical`和`multiple`，意味着拼接长图和多图，所有图片的链接在imgUrls里
     * 一种单张图片: `single` 图片链接也在imgUrls里
     * K歌: `ksong` 图片链接一样，不考虑爬取音频...
     * 视频: `video` 需要解析html获得视频链接
    '''


def __doufu_work(uid, dir, work, wdx):
    w_type = work['workType']
    w_caption = re.sub(r"\s+", " ", work['caption'])
    w_name2 = re.sub(r'[\\/:*?"<>|\r\n]+', "", w_caption)[0:24]
    emoji_str = emoji.demojize(w_name2)
    w_name = re.sub(r':(.*?):', '', emoji_str).strip()
    w_time = time.strftime('%Y年%m月%d日%H时%M分%S秒', time.localtime(work['timestamp'] / 1000))
    w_time_old = time.strftime('%Y-%m-%d', time.localtime(work['timestamp'] / 1000))
    w_index = ""
    global __date_cache
    global __date_count
    if __date_cache == w_time:
        __date_count = __date_count + 1
        if __date_count > 0:
            w_index = "(%d)" % __date_count
    else:
        __date_cache = w_time
        __date_count = 0

    if w_type == 'vertical' or w_type == 'multiple' or w_type == "single" or w_type == 'ksong':
        if var7.get() == 0:
            w_name2 = re.sub(r'[.*?"<>|\r\n]+', "", w_name)
            tuji_name = w_time + "_" + work['id'] + "_" + w_name2
            tujiid = work['id']
            tuji_lujing = dir + "图集/"
            tuji = tuji_lujing + tuji_name
            if not os.path.exists(tuji_lujing):
                tuji_list = []
            else:
                tuji_list = os.listdir(tuji_lujing)

            for tuji_jici in range(len(tuji_list)):
                if tujiid in tuji_list[tuji_jici]:
                    text.insert(END, "    图集 " + tuji_name + " 已存在 √")
                    text.update()
                    text.see(END)
                    text.insert(END, "丨图集已存在 √丨")
                    text.update()
                    text.see(END)
                    QJ.exists += 1
                    #print(QJ.bakuid + "图集或视频已存在出现了" + str(QJ.exists) + "次")
                    yichuxiancishu["text"] = "用户:" + QJ.bakname + ",UID:" + QJ.bakuid + ",已存在" + str(QJ.exists) + "次"
                    text.insert(END, "丨" + QJ.bakuid + "图集或视频已存在出现了" + str(QJ.exists) + "次" + "丨")
                    text.update()
                    text.see(END)
                    break
                elif w_time_old in tuji_list[tuji_jici]:
                    text.insert(END, "    图集 " + tuji_name + " 已存在 √")
                    text.update()
                    text.see(END)
                    text.insert(END, "丨图集已存在 √丨")
                    text.update()
                    text.see(END)
                    QJ.exists += 1
                    #print(QJ.bakuid + "图集或视频已存在出现了" + str(QJ.exists) + "次")
                    yichuxiancishu["text"] = "用户:" + QJ.bakname + ",UID:" + QJ.bakuid + ",已存在" + str(QJ.exists) + "次"
                    text.insert(END, "丨"  + QJ.bakuid + "图集或视频已存在出现了" + str(QJ.exists) + "次" + "丨" )
                    text.update()
                    text.see(END)
                    break

                        # text.insert(END, QJ.bakuid + "图集或视频已存在出现了" + str(QJ.exists) + "次")
                        # text.update()
                        # text.see(END)
            else:
                QJ.exists = 0
                w_urls = work['imgUrls']
                l = len(w_urls)
                text.insert(END, "  " + str(wdx) + ")图集作品：" + w_caption + "，" + "共有" + str(l) + "张图片")
                text.update()
                text.see(END)
                for i in range(l):
                    p_name = w_time + "_" + work['id'] + "_" + w_name + "_" + str(i + 1) + '.jpg'
                    w_name2 = re.sub(r'[.*?"<>|\r\n]+', "", w_name)
                    dir2 = dir + "图集/" + w_time + "_" + work['id'] + "_" + w_name2 + "/"
                    if not os.path.exists(dir2):
                        os.makedirs(dir2)
                    pic = dir2 + p_name
                    if not os.path.exists(pic):
                        while True:  # 一直循环，知道访问站点成功
                            try:
                                # 以下except都是用来捕获当requests请求出现异常时，
                                # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
                                requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
                                r = requests.get(w_urls[i].replace("webp", "jpg"), verify=False)
                                r.raise_for_status()
                                break
                            except requests.exceptions.HTTPError:
                                text.insert(END, "HTTPError, 等待5秒后再次下载!!!")
                                text.update()
                                text.see(END)
                                time.sleep(5)
                            except requests.exceptions.ConnectionError:
                                text.insert(END, "ConnectionError, 等待5秒后再次下载!!!")
                                text.update()
                                text.see(END)
                                time.sleep(5)
                            except requests.exceptions.ChunkedEncodingError:
                                text.insert(END, "ChunkedEncodingError, 等待5秒后再次下载!!!")
                                text.update()
                                text.see(END)
                                time.sleep(5)
                            except:
                                text.insert(END, "Unfortunitely -- An Unknow Error Happened, 等待60秒后程序重新运行!!!")
                                text.update()
                                text.see(END)
                                time.sleep(60)
                                restart_program()

                        with open(pic, "wb") as f:
                            f.write(r.content)
                        text.insert(END, "    " + str(i + 1) + "/" + str(l) + " 图片 " + p_name + " 下载成功 √")
                        text.update()
                        text.see(END)
                        text.insert(END, "图集地址:")
                        text.update()
                        text.see(END)
                        text.insert(END, w_urls[i])
                        text.update()
                        text.see(END)
                        text.insert(END, "丨图片下载成功 √丨")
                        text.update()
                        text.see(END)
                    else:
                        text.insert(END, "    " + str(i + 1) + "/" + str(l) + " 图片 " + p_name + " 已存在 √")
                        text.update()
                        text.see(END)
                        text.insert(END, "丨图片已存在 √丨")
                        text.update()
                        text.see(END)
    elif w_type == 'video':
        if var3.get() == 0:
            v_name = w_time + "_" + work['id'] + "_" + w_name + ".mp4"
            shipinid = work['id']
            dir2 = dir + "视频/"
            video = dir2 + v_name
            if not os.path.exists(dir2):
                video_list = []
            else:
                video_list = os.listdir(dir2)
            for video_jici in range(len(video_list)):
                if shipinid in video_list[video_jici]:
                    text.insert(END, "    视频 " + v_name + " 已存在 √")
                    text.update()
                    text.see(END)
                    text.insert(END, "丨视频已存在 √丨")
                    text.update()
                    text.see(END)
                    QJ.exists += 1
                    #print(QJ.bakuid + "图集或视频已存在出现了" + str(QJ.exists) + "次")
                    yichuxiancishu["text"] = "用户:" + QJ.bakname + ",UID:" + QJ.bakuid + ",已存在" + str(QJ.exists) + "次"
                    text.insert(END, "丨" + QJ.bakuid + "图集或视频已存在出现了" + str(QJ.exists) + "次" + "丨")
                    text.update()
                    text.see(END)
                    break
                elif w_time_old in video_list[video_jici]:
                    text.insert(END, "    视频 " + v_name + " 已存在 √")
                    text.update()
                    text.see(END)
                    text.insert(END, "丨视频已存在 √丨")
                    text.update()
                    text.see(END)
                    QJ.exists += 1
                    #print(QJ.bakuid + "图集或视频已存在出现了" + str(QJ.exists) + "次")
                    yichuxiancishu["text"] = "用户:" + QJ.bakname + ",UID:" + QJ.bakuid + ",已存在" + str(QJ.exists) + "次"
                    text.insert(END, "丨" + QJ.bakuid + "图集或视频已存在出现了" + str(QJ.exists) + "次" + "丨")
                    text.update()
                    text.see(END)
                    break
                        # text.insert(END, QJ.bakuid + "图集或视频已存在出现了" + str(QJ.exists) + "次")
                        # text.update()
                        # text.see(END)
            else:
                QJ.exists = 0
                w_url = WORK_URL + work['id'] + "?fid=" + QJ.find_url1_last + "&photoId=" + work['id'] + "&shareId=" + QJ.find_url2_last + "&userId=" + QJ.bak_uid + "&shareType=" + QJ.find_url3_last + "&timestamp=" + str(int(round(time.time() * 1000)))
                while True:  # 一直循环，知道访问站点成功
                    try:
                        # 以下except都是用来捕获当requests请求出现异常时，
                        # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
                        requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
                        res = requests.get(w_url, headers=__headers_mobile, verify=False)
                        res.raise_for_status()
                        break
                    except requests.exceptions.HTTPError:
                        text.insert(END, "HTTPError, 等待5秒后再次下载!!!")
                        text.update()
                        text.see(END)
                        time.sleep(5)
                    except requests.exceptions.ConnectionError:
                        text.insert(END, "ConnectionError, 等待5秒后再次下载!!!")
                        text.update()
                        text.see(END)
                        time.sleep(5)
                    except requests.exceptions.ChunkedEncodingError:
                        text.insert(END, "ChunkedEncodingError, 等待5秒后再次下载!!!")
                        text.update()
                        text.see(END)
                        time.sleep(5)
                    except:
                        text.insert(END, "Unfortunitely -- An Unknow Error Happened, 等待60秒后程序重新运行!!!")
                        text.update()
                        text.see(END)
                        time.sleep(60)
                        restart_program()
                # res = requests.get(w_url, headers=__headers_mobile, verify=False)
                #requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

                # payload1 = {"operationName": "SharePageQuery",
                #            "variables": {"photoId": work['id'], "principalId": uid},
                #            "query": "query SharePageQuery($principalId: String, $photoId: String) {\n  feedById(principalId: $principalId, photoId: $photoId) {\n    currentWork {\n      playUrl\n      __typename\n    }\n    __typename\n  }\n}\n"}
                # res1 = requests.post(DATA_URL, headers=__headers_web, json=payload1)
                # html1 = json.loads(res1.content.decode(encoding='utf-8', errors='strict'))['data']['feedById']['currentWork']
                # v_url = html1['playUrl']

                html = res.text
                waitreplace2 = work['id'] + '&#34.*?&#34;srcNoMark&#34;:&#34;(.*?)&#34;'
                v_url2 = re.findall(waitreplace2, html)
                if v_url2 == []:
                    waitreplace = '"srcNoMark":"(.*?)"},"user"'
                else:
                    waitreplace = work['id'] + '&#34.*?&#34;srcNoMark&#34;:&#34;(.*?)&#34;'


                yzm_jici = 0
                while html.find('操作太快了，请稍微休息一下') != -1:
                    text.insert(END, "出现操作太快了!!!可能触发反爬机制------60秒后再次重新打开浏览器获取cook!!!")
                    text.update()
                    text.see(END)
                    QJ.ua_list_ = ua_list[random.randint(0, 28)]
                    text.insert(END, "定义浏览器移动端标识(User-Agent):" + QJ.ua_list_)
                    text.update()
                    text.see(END)
                    __headers_mobile[
                        'Cookie'] = ''  # 'did=' + did + ';userId=' + did5 + ';didv=' + str(int(time.time()) * 1000) + ';sid=' + QJ.sid_cook
                    time.sleep(60)
                    options = webdriver.ChromeOptions()
                    options.add_argument(
                        'User-Agent=' + QJ.ua_list_)
                    driver = webdriver.Chrome(executable_path="Google Chrome/chromedriver.exe", chrome_options=options)
                    if len(QJ.duanlian_list) == 1:
                        QJ.duanlian = QJ.duanlian_list[0]
                    else:
                        QJ.duanlian = QJ.duanlian_list[random.randint(0, len(QJ.duanlian_list) - 1)]
                    text.insert(END, "当前选择的分享短链:" + QJ.duanlian)
                    text.update()
                    text.see(END)
                    driver.get(QJ.duanlian)
                    #driver.implicitly_wait(30)
                    file = '提示音.wav'  # 文件名是完整路径名
                    # divs = driver.find_elements_by_tag_name('div')
                    # for div in divs:
                    #     if '继续观看内容' in div.text:
                    #         divs1 = driver.find_elements_by_tag_name('div')
                    #         for div1 in divs1:
                    #             if '继续观看' in div1.text:
                    #                 div1.click()
                    #     else:
                    #         break

                    time.sleep(3)
                    iframes = driver.find_elements_by_tag_name("iframe")
                    if iframes != []:
                        time.sleep(1)
                        driver.refresh()
                        time.sleep(1)
                        iframes = driver.find_elements_by_tag_name("iframe")
                    while iframes != []:
                        # driver.implicitly_wait(30)
                        pygame.mixer.init()  # 初始化音频
                        track = pygame.mixer.music.load(file)  # 载入音乐文件
                        pygame.mixer.music.play()  # 开始播放
                        time.sleep(3)
                        iframes = driver.find_elements_by_tag_name("iframe")
                        if iframes != []:
                            text.insert(END, "出现验证码弹窗请等待自动验证或者自动验证失败后在手动验证")
                            text.update()
                            text.see(END)
                            iframe = driver.find_elements_by_tag_name("iframe")[0]
                            driver.switch_to.default_content()
                            driver.switch_to.frame(iframe)
                            bgtu = driver.find_element_by_xpath('/html/body/div/div/div[1]/img[1]')
                            bgtu_link = bgtu.get_attribute("src")
                            # r = requests.get(bgtu_link, verify=False)
                            while True:  # 一直循环，知道访问站点成功
                                try:
                                    # 以下except都是用来捕获当requests请求出现异常时，
                                    # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
                                    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
                                    r = requests.get(bgtu_link, verify=False)
                                    r.raise_for_status()
                                    # res = requests.get(w_url, headers=__headers_mobile, verify=False)
                                    # res.raise_for_status()
                                    break
                                except requests.exceptions.HTTPError:
                                    text.insert(END, "HTTPError, 等待5秒后再次下载!!!")
                                    text.update()
                                    text.see(END)
                                    time.sleep(5)
                                except requests.exceptions.ConnectionError:
                                    text.insert(END, "ConnectionError, 等待5秒后再次下载!!!")
                                    text.update()
                                    text.see(END)
                                    time.sleep(5)
                                except requests.exceptions.ChunkedEncodingError:
                                    text.insert(END, "ChunkedEncodingError, 等待5秒后再次下载!!!")
                                    text.update()
                                    text.see(END)
                                    time.sleep(5)
                                except:
                                    text.insert(END, "Unfortunitely -- An Unknow Error Happened, 等待60秒后程序重新运行!!!")
                                    text.update()
                                    text.see(END)
                                    time.sleep(60)
                                    restart_program()
                            dir = "./"
                            # if not os.path.exists(dir):
                            #     os.makedirs(dir)
                            bjtu_pic = dir + "2.png"
                            with open(bjtu_pic, "wb") as f:
                                f.write(r.content)
                            slidertu = driver.find_element_by_xpath('/html/body/div/div/div[1]/img[2]')
                            slidertu_link = slidertu.get_attribute("src")
                            # r = requests.get(slidertu_link, verify=False)
                            while True:  # 一直循环，知道访问站点成功
                                try:
                                    # 以下except都是用来捕获当requests请求出现异常时，
                                    # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
                                    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
                                    r = requests.get(slidertu_link, verify=False)
                                    r.raise_for_status()
                                    # res = requests.get(w_url, headers=__headers_mobile, verify=False)
                                    # res.raise_for_status()
                                    break
                                except requests.exceptions.HTTPError:
                                    text.insert(END, "HTTPError, 等待5秒后再次下载!!!")
                                    text.update()
                                    text.see(END)
                                    time.sleep(5)
                                except requests.exceptions.ConnectionError:
                                    text.insert(END, "ConnectionError, 等待5秒后再次下载!!!")
                                    text.update()
                                    text.see(END)
                                    time.sleep(5)
                                except requests.exceptions.ChunkedEncodingError:
                                    text.insert(END, "ChunkedEncodingError, 等待5秒后再次下载!!!")
                                    text.update()
                                    text.see(END)
                                    time.sleep(5)
                                except:
                                    text.insert(END, "Unfortunitely -- An Unknow Error Happened, 等待60秒后程序重新运行!!!")
                                    text.update()
                                    text.see(END)
                                    time.sleep(60)
                                    restart_program()
                            dir = "./"
                            # if not os.path.exists(dir):
                            #     os.makedirs(dir)
                            slider_pic = dir + "1.png"
                            with open(slider_pic, "wb") as f:
                                f.write(r.content)
                            image_pyramid()
                            image_contrast()
                            huakuai = driver.find_element_by_xpath('/html/body/div/div/div[2]/div[2]/div/i')
                            time.sleep(1)
                            # move_to_gap(huakuai, get_track(340))
                            ActionChains(driver).click_and_hold(huakuai).perform()
                            for x in get_track(QJ.max_x * 4 - 25):
                                ActionChains(driver).move_by_offset(xoffset=x, yoffset=0).perform()
                            time.sleep(0.5)
                            ActionChains(driver).release().perform()
                            time.sleep(5)
                            driver.switch_to.default_content()
                            time.sleep(1)
                            # driver.refresh()
                            pygame.mixer.music.stop()  # 停止播放
                            iframes = driver.find_elements_by_tag_name("iframe")
                            if iframes == []:
                                break
                            else:
                                driver.refresh()
                    pygame.mixer.music.stop()
                    cookie5 = [item['name'] + '=' + item['value'] for item in driver.get_cookies()]
                    cookie3 = [item['name'] for item in driver.get_cookies()]
                    cookie4 = [item['value'] for item in driver.get_cookies()]
                    sep = "; "
                    QJ.cookie_mobile = sep.join(cookie5)
                    for cookie3_jici in range(len(cookie3)):
                        if cookie3[cookie3_jici] == "sid":
                            QJ.sid_cook = cookie4[cookie3_jici]
                            break
                    driver.close()
                    __headers_mobile[
                        'Cookie'] = QJ.cookie_mobile  # 'did=' + did + ';userId=' + did5 + ';didv=' + str(int(time.time()) * 1000) + ';sid=' + QJ.sid_cook
                    w_url = WORK_URL + work['id'] + "?fid=" + QJ.find_url1_last + "&photoId=" + work['id'] + "&shareId=" + QJ.find_url2_last + "&userId=" + QJ.bak_uid + "&shareType=" + QJ.find_url3_last + "&timestamp=" + str(int(round(time.time() * 1000)))
                    while True:  # 一直循环，知道访问站点成功
                        try:
                            # 以下except都是用来捕获当requests请求出现异常时，
                            # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
                            requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
                            res = requests.get(w_url, headers=__headers_mobile, verify=False)
                            res.raise_for_status()
                            break
                        except requests.exceptions.HTTPError:
                            text.insert(END, "HTTPError, 等待5秒后再次下载!!!")
                            text.update()
                            text.see(END)
                            time.sleep(5)
                        except requests.exceptions.ConnectionError:
                            text.insert(END, "ConnectionError, 等待5秒后再次下载!!!")
                            text.update()
                            text.see(END)
                            time.sleep(5)
                        except requests.exceptions.ChunkedEncodingError:
                            text.insert(END, "ChunkedEncodingError, 等待5秒后再次下载!!!")
                            text.update()
                            text.see(END)
                            time.sleep(5)
                        except:
                            text.insert(END, "Unfortunitely -- An Unknow Error Happened, 等待60秒后程序重新运行!!!")
                            text.update()
                            text.see(END)
                            time.sleep(60)
                            restart_program()
                    # res = requests.get(w_url, headers=__headers_mobile, verify=False)
                    # res = requests.get(w_url, headers=__headers_mobile, verify=False)
                    # w_url = WORK_URL + work['id']
                    # res = requests.get(w_url, headers=__headers_mobile, verify=False,
                    #                    params={"fid": int(QJ.userid_cook), "cc": "share_copylink",
                    #                            "shareId": "143108986354"})

                    #requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

                    # payload1 = {"operationName": "SharePageQuery",
                    #            "variables": {"photoId": work['id'], "principalId": uid},
                    #            "query": "query SharePageQuery($principalId: String, $photoId: String) {\n  feedById(principalId: $principalId, photoId: $photoId) {\n    currentWork {\n      playUrl\n      __typename\n    }\n    __typename\n  }\n}\n"}
                    # res1 = requests.post(DATA_URL, headers=__headers_web, json=payload1)
                    # html1 = json.loads(res1.content.decode(encoding='utf-8', errors='strict'))['data']['feedById']['currentWork']
                    # v_url = html1['playUrl']

                    html = res.text
                    waitreplace2 = work['id'] + '&#34.*?&#34;srcNoMark&#34;:&#34;(.*?)&#34;'
                    v_url2 = re.findall(waitreplace2, html)
                    if v_url2 == []:
                        waitreplace = '"srcNoMark":"(.*?)"},"user"'
                    else:
                        waitreplace = work['id'] + '&#34.*?&#34;srcNoMark&#34;:&#34;(.*?)&#34;'
                    yzm_jici = yzm_jici + 1
                    if yzm_jici == QJ.yzm_num:
                        restart_program()


                    # payload1 = {"operationName": "SharePageQuery",
                    #            "variables": {"photoId": work['id'], "principalId": uid},
                    #            "query": "query SharePageQuery($principalId: String, $photoId: String) {\n  feedById(principalId: $principalId, photoId: $photoId) {\n    currentWork {\n      playUrl\n      __typename\n    }\n    __typename\n  }\n}\n"}
                    # res1 = requests.post(DATA_URL, headers=__headers_web, json=payload1)
                    # html1 = json.loads(res1.content.decode(encoding='utf-8', errors='strict'))['data']['feedById']['currentWork']
                    # v_url = html1['playUrl']

                    # doufu()

                # if html.find('快手验证码') != -1:
                #     text.insert(END, "出现验证码了!!!可能触发反爬机制------60秒后程序自动重新运行!!!")
                #     text.update()
                #     text.see(END)
                #     time.sleep(60)
                #     restart_program()
                yzm_jici1 = 0
                while html.find('快手验证码') != -1:
                    text.insert(END, "出现验证码了!!!可能触发反爬机制------60秒后再次重新打开浏览器获取cook!!!")
                    text.update()
                    text.see(END)
                    QJ.ua_list_ = ua_list[random.randint(0, 28)]
                    text.insert(END, "定义浏览器移动端标识(User-Agent):" + QJ.ua_list_)
                    text.update()
                    text.see(END)
                    __headers_mobile[
                        'Cookie'] = ''  # 'did=' + did + ';userId=' + did5 + ';didv=' + str(int(time.time()) * 1000) + ';sid=' + QJ.sid_cook
                    time.sleep(60)
                    options = webdriver.ChromeOptions()
                    options.add_argument(
                        'User-Agent=' + QJ.ua_list_)
                    driver = webdriver.Chrome(executable_path="Google Chrome/chromedriver.exe", chrome_options=options)
                    if len(QJ.duanlian_list) == 1:
                        QJ.duanlian = QJ.duanlian_list[0]
                    else:
                        QJ.duanlian = QJ.duanlian_list[random.randint(0, len(QJ.duanlian_list) - 1)]
                    text.insert(END, "当前选择的分享短链:" + QJ.duanlian)
                    text.update()
                    text.see(END)
                    driver.get(QJ.duanlian)
                    #driver.implicitly_wait(30)
                    file = '提示音.wav'  # 文件名是完整路径名
                    # divs = driver.find_elements_by_tag_name('div')
                    # for div in divs:
                    #     if '继续观看内容' in div.text:
                    #         divs1 = driver.find_elements_by_tag_name('div')
                    #         for div1 in divs1:
                    #             if '继续观看' in div1.text:
                    #                 div1.click()
                    #     else:
                    #         break

                    time.sleep(3)
                    iframes = driver.find_elements_by_tag_name("iframe")
                    if iframes != []:
                        time.sleep(1)
                        driver.refresh()
                        time.sleep(1)
                        iframes = driver.find_elements_by_tag_name("iframe")
                    while iframes != []:
                        # driver.implicitly_wait(30)
                        pygame.mixer.init()  # 初始化音频
                        track = pygame.mixer.music.load(file)  # 载入音乐文件
                        pygame.mixer.music.play()  # 开始播放
                        time.sleep(3)
                        iframes = driver.find_elements_by_tag_name("iframe")
                        if iframes != []:
                            text.insert(END, "出现验证码弹窗请等待自动验证或者自动验证失败后在手动验证")
                            text.update()
                            text.see(END)
                            iframe = driver.find_elements_by_tag_name("iframe")[0]
                            driver.switch_to.default_content()
                            driver.switch_to.frame(iframe)
                            bgtu = driver.find_element_by_xpath('/html/body/div/div/div[1]/img[1]')
                            bgtu_link = bgtu.get_attribute("src")
                            # r = requests.get(bgtu_link, verify=False)
                            while True:  # 一直循环，知道访问站点成功
                                try:
                                    # 以下except都是用来捕获当requests请求出现异常时，
                                    # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
                                    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
                                    r = requests.get(bgtu_link, verify=False)
                                    r.raise_for_status()
                                    # res = requests.get(w_url, headers=__headers_mobile, verify=False)
                                    # res.raise_for_status()
                                    break
                                except requests.exceptions.HTTPError:
                                    text.insert(END, "HTTPError, 等待5秒后再次下载!!!")
                                    text.update()
                                    text.see(END)
                                    time.sleep(5)
                                except requests.exceptions.ConnectionError:
                                    text.insert(END, "ConnectionError, 等待5秒后再次下载!!!")
                                    text.update()
                                    text.see(END)
                                    time.sleep(5)
                                except requests.exceptions.ChunkedEncodingError:
                                    text.insert(END, "ChunkedEncodingError, 等待5秒后再次下载!!!")
                                    text.update()
                                    text.see(END)
                                    time.sleep(5)
                                except:
                                    text.insert(END, "Unfortunitely -- An Unknow Error Happened, 等待60秒后程序重新运行!!!")
                                    text.update()
                                    text.see(END)
                                    time.sleep(60)
                                    restart_program()
                            dir = "./"
                            # if not os.path.exists(dir):
                            #     os.makedirs(dir)
                            bjtu_pic = dir + "2.png"
                            with open(bjtu_pic, "wb") as f:
                                f.write(r.content)
                            slidertu = driver.find_element_by_xpath('/html/body/div/div/div[1]/img[2]')
                            slidertu_link = slidertu.get_attribute("src")
                            # r = requests.get(slidertu_link, verify=False)
                            while True:  # 一直循环，知道访问站点成功
                                try:
                                    # 以下except都是用来捕获当requests请求出现异常时，
                                    # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
                                    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
                                    r = requests.get(slidertu_link, verify=False)
                                    r.raise_for_status()
                                    # res = requests.get(w_url, headers=__headers_mobile, verify=False)
                                    # res.raise_for_status()
                                    break
                                except requests.exceptions.HTTPError:
                                    text.insert(END, "HTTPError, 等待5秒后再次下载!!!")
                                    text.update()
                                    text.see(END)
                                    time.sleep(5)
                                except requests.exceptions.ConnectionError:
                                    text.insert(END, "ConnectionError, 等待5秒后再次下载!!!")
                                    text.update()
                                    text.see(END)
                                    time.sleep(5)
                                except requests.exceptions.ChunkedEncodingError:
                                    text.insert(END, "ChunkedEncodingError, 等待5秒后再次下载!!!")
                                    text.update()
                                    text.see(END)
                                    time.sleep(5)
                                except:
                                    text.insert(END, "Unfortunitely -- An Unknow Error Happened, 等待60秒后程序重新运行!!!")
                                    text.update()
                                    text.see(END)
                                    time.sleep(60)
                                    restart_program()
                            dir = "./"
                            # if not os.path.exists(dir):
                            #     os.makedirs(dir)
                            slider_pic = dir + "1.png"
                            with open(slider_pic, "wb") as f:
                                f.write(r.content)
                            image_pyramid()
                            image_contrast()
                            huakuai = driver.find_element_by_xpath('/html/body/div/div/div[2]/div[2]/div/i')
                            time.sleep(1)
                            # move_to_gap(huakuai, get_track(340))
                            ActionChains(driver).click_and_hold(huakuai).perform()
                            for x in get_track(QJ.max_x * 4 - 25):
                                ActionChains(driver).move_by_offset(xoffset=x, yoffset=0).perform()
                            time.sleep(0.5)
                            ActionChains(driver).release().perform()
                            time.sleep(5)
                            driver.switch_to.default_content()
                            time.sleep(1)
                            # driver.refresh()
                            pygame.mixer.music.stop()  # 停止播放
                            iframes = driver.find_elements_by_tag_name("iframe")
                            if iframes == []:
                                break
                            else:
                                driver.refresh()
                    pygame.mixer.music.stop()
                    cookie5 = [item['name'] + '=' + item['value'] for item in driver.get_cookies()]
                    cookie3 = [item['name'] for item in driver.get_cookies()]
                    cookie4 = [item['value'] for item in driver.get_cookies()]
                    sep = "; "
                    QJ.cookie_mobile = sep.join(cookie5)
                    for cookie3_jici in range(len(cookie3)):
                        if cookie3[cookie3_jici] == "sid":
                            QJ.sid_cook = cookie4[cookie3_jici]
                            break
                    driver.close()
                    __headers_mobile[
                        'Cookie'] = QJ.cookie_mobile  # 'did=' + did + ';userId=' + did5 + ';didv=' + str(int(time.time()) * 1000) + ';sid=' + QJ.sid_cook
                    w_url = WORK_URL + work['id'] + "?fid=" + QJ.find_url1_last + "&photoId=" + work['id'] + "&shareId=" + QJ.find_url2_last + "&userId=" + QJ.bak_uid + "&shareType=" + QJ.find_url3_last + "&timestamp=" + str(int(round(time.time() * 1000)))
                    while True:  # 一直循环，知道访问站点成功
                        try:
                            # 以下except都是用来捕获当requests请求出现异常时，
                            # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
                            requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
                            res = requests.get(w_url, headers=__headers_mobile, verify=False)
                            res.raise_for_status()
                            break
                        except requests.exceptions.HTTPError:
                            text.insert(END, "HTTPError, 等待5秒后再次下载!!!")
                            text.update()
                            text.see(END)
                            time.sleep(5)
                        except requests.exceptions.ConnectionError:
                            text.insert(END, "ConnectionError, 等待5秒后再次下载!!!")
                            text.update()
                            text.see(END)
                            time.sleep(5)
                        except requests.exceptions.ChunkedEncodingError:
                            text.insert(END, "ChunkedEncodingError, 等待5秒后再次下载!!!")
                            text.update()
                            text.see(END)
                            time.sleep(5)
                        except:
                            text.insert(END, "Unfortunitely -- An Unknow Error Happened, 等待60秒后程序重新运行!!!")
                            text.update()
                            text.see(END)
                            time.sleep(60)
                            restart_program()
                    # res = requests.get(w_url, headers=__headers_mobile, verify=False)
                    # w_url = WORK_URL + work['id']
                    # res = requests.get(w_url, headers=__headers_mobile, verify=False,
                    #                    params={"fid": int(QJ.userid_cook), "cc": "share_copylink",
                    #                            "shareId": "143108986354"})

                    #requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

                    # payload1 = {"operationName": "SharePageQuery",
                    #            "variables": {"photoId": work['id'], "principalId": uid},
                    #            "query": "query SharePageQuery($principalId: String, $photoId: String) {\n  feedById(principalId: $principalId, photoId: $photoId) {\n    currentWork {\n      playUrl\n      __typename\n    }\n    __typename\n  }\n}\n"}
                    # res1 = requests.post(DATA_URL, headers=__headers_web, json=payload1)
                    # html1 = json.loads(res1.content.decode(encoding='utf-8', errors='strict'))['data']['feedById']['currentWork']
                    # v_url = html1['playUrl']

                    html = res.text
                    waitreplace2 = work['id'] + '&#34.*?&#34;srcNoMark&#34;:&#34;(.*?)&#34;'
                    v_url2 = re.findall(waitreplace2, html)
                    if v_url2 == []:
                        waitreplace = '"srcNoMark":"(.*?)"},"user"'
                    else:
                        waitreplace = work['id'] + '&#34.*?&#34;srcNoMark&#34;:&#34;(.*?)&#34;'
                    yzm_jici1 = yzm_jici1 + 1
                    if yzm_jici1 == QJ.yzm_num:
                        restart_program()

                        # doufu()

                v_url = re.findall(waitreplace, html)
                # pattern = re.compile(r"playUrl", re.MULTILINE | re.DOTALL)
                # script = soup.find("script", text=pattern)
                # s = pattern.search(script.text).string
                # v_url = s.split('playUrl":"')[1].split('.mp4')[0].encode('utf-8').decode('unicode-escape') + '.mp4'
                try:
                    text.insert(END, "  " + str(wdx) + ")视频作品：" + "丨" + w_time + "丨" + work['id'] + "丨" + w_name)
                    text.update()
                    text.see(END)
                except:
                    text.insert(END, "  这里似乎有点小错误，已跳过")
                    text.update()
                    text.see(END)
                # v_name = w_time + w_index + "_" + w_name + ".mp4"
                v_name = w_time + "_" + work['id'] + "_" + w_name + ".mp4"
                dir2 = dir + "视频/"
                if not os.path.exists(dir2):
                    os.makedirs(dir2)
                # video = dir2 + v_name
                video = dir2 + v_name

                if v_url:
                    if not os.path.exists(video):
                        # r = requests.get(v_url)
                        # r = requests.get(v_url[0])
                        # r.raise_for_status()
                        while True:  # 一直循环，知道访问站点成功
                            try:
                                # 以下except都是用来捕获当requests请求出现异常时，
                                # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
                                requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
                                #print(v_url[0])
                                if "kwai://" in v_url[0]:
                                    waitreplace_v_url = 'http(.*?)","'
                                    v_url_panduan = re.findall(waitreplace_v_url, v_url[0])
                                    for v_url_panduan_jici in range(0, len(v_url_panduan)):
                                        if ".mp4" in v_url_panduan[v_url_panduan_jici]:
                                            v_url[0] = "http" + v_url_panduan[v_url_panduan_jici]
                                            break
                                    # if ".mp4" in v_url_panduan[0]:
                                    #     v_url[0] =  "http" + v_url_panduan[0]
                                    # else:
                                    #     for v_url_panduan_jici in range(0, len(v_url_panduan)):
                                    #         if ".mp4" in v_url_panduan[v_url_panduan_jici]:
                                    #             v_url[0] = "http" + v_url_panduan[v_url_panduan_jici]
                                    #             break
                                r = requests.get(v_url[0], verify=False)
                                r.raise_for_status()
                                #res = requests.get(w_url, headers=__headers_mobile, verify=False)
                                #res.raise_for_status()
                                break
                            except requests.exceptions.HTTPError:
                                text.insert(END, "HTTPError, 等待5秒后再次下载!!!")
                                text.update()
                                text.see(END)
                                time.sleep(5)
                            except requests.exceptions.ConnectionError:
                                text.insert(END, "ConnectionError, 等待5秒后再次下载!!!")
                                text.update()
                                text.see(END)
                                time.sleep(5)
                            except requests.exceptions.ChunkedEncodingError:
                                text.insert(END, "ChunkedEncodingError, 等待5秒后再次下载!!!")
                                text.update()
                                text.see(END)
                                time.sleep(5)
                            except:
                                text.insert(END, "Unfortunitely -- An Unknow Error Happened, 等待60秒后重启程序!!!")
                                text.update()
                                text.see(END)
                                time.sleep(60)
                                restart_program()

                        with open(video, "wb") as f:
                            f.write(r.content)
                        text.insert(END, "    视频 " + v_name + " 下载成功 √")
                        text.update()
                        text.see(END)
                        text.insert(END, "视频地址:")
                        text.update()
                        text.see(END)
                        text.insert(END, v_url[0])
                        text.update()
                        text.see(END)
                        text.insert(END, "丨视频下载成功 √丨")
                        text.update()
                        text.see(END)
                    else:
                        text.insert(END, "    视频 " + v_name + " 已存在 √")
                        text.update()
                        text.see(END)
                        text.insert(END, "丨视频已存在 √丨")
                        text.update()
                        text.see(END)
                else:
                    text.insert(END, "未找到视频-----继续执行下一个!!!")
                    text.update()
                    text.see(END)
                    # time.sleep(60)
                    # restart_program()
                    # doufu()
    else:
        text.insert(END, "错误的类型-----60秒后程序自动重新运行!!!")
        text.update()
        text.see(END)
        time.sleep(60)
        restart_program()
        #doufu()


def __read_preset():
    p_path = "uid.txt"
    if not os.path.exists(p_path):
        #print("创建预设文件 uid ...")
        print("创建预设文件 uid ...")
        open(p_path, "w")
        exit(0)
    p_path1 = "没有作品.txt"
    if not os.path.exists(p_path1):
        # print("创建预设文件 uid ...")
        print("创建预设文件 没有作品.txt ...")
        open(p_path1, "w")
        exit(0)
    if not os.path.getsize(p_path):
        #print("请在预设文件 uid 中记录需要爬取的用户id，一行一个")
        print("请在预设文件 uid 中记录需要爬取的用户id，一行一个")
        exit(0)
    with open(p_path, "r") as f:
        for line in f:
            if line[0] != "#":
                QJ.doufu_list__.append(line.strip())


def __switch_id(uid):
    payload = {"operationName": "SearchOverviewQuery",
               "variables": {"keyword": uid, "ussid": None},
               "query": "query SearchOverviewQuery($keyword: String, $ussid: String) {\n  pcSearchOverview(keyword: $keyword, ussid: $ussid) {\n    list {\n      ... on SearchCategoryList {\n        type\n        list {\n          categoryId\n          categoryAbbr\n          title\n          src\n          __typename\n        }\n        __typename\n      }\n      ... on SearchUserList {\n        type\n        ussid\n        list {\n          id\n          name\n          living\n          avatar\n          sex\n          description\n          counts {\n            fan\n            follow\n            photo\n            __typename\n          }\n          __typename\n        }\n        __typename\n      }\n      ... on SearchLivestreamList {\n        type\n        lssid\n        list {\n          user {\n            id\n            avatar\n            name\n            __typename\n          }\n          poster\n          coverUrl\n          caption\n          id\n          playUrls {\n            quality\n            url\n            __typename\n          }\n          quality\n          gameInfo {\n            category\n            name\n            pubgSurvival\n            type\n            kingHero\n            __typename\n          }\n          hasRedPack\n          liveGuess\n          expTag\n          __typename\n        }\n        __typename\n      }\n      __typename\n    }\n    __typename\n  }\n}\n"}

    res = requests.post(DATA_URL, headers=__headers_web, json=payload)
    dt = json.loads(res.content.decode(encoding='utf-8', errors='strict'))['data']
    # with open("data/jj_" + uid + ".json", "w") as fp:
    #     fp.write(json.dumps(dt, indent=2))

    return dt['pcSearchOverview']['list'][1]['list'][0]['id']


'''
try:
    bgtu = driver.find_element_by_xpath('/html/body/div/div/div[1]/img[1]')
except NoSuchElementException as msg:
    print("查找元素异常%s"%msg)

NoSuchElementException：没有找到元素

NoSuchFrameException：没有找到iframe

NoSuchWindowException:没找到窗口句柄handle

NoSuchAttributeException:属性错误

NoAlertPresentException：没找到alert弹出框

lementNotVisibleException：元素不可见

ElementNotSelectableException：元素没有被选中

TimeoutException：查找元素超时
'''

def __openchrome():
    if var8.get() == 0:
        if QJ.duanlian_list[0] == "":
            text.insert(END, "请在config.ini配置文件中填入分享短链!!!")
            text.update()
            text.see(END)
            time.sleep(5)
            root.quit()
        else:
            if len(QJ.duanlian_list) == 1:
                QJ.duanlian = QJ.duanlian_list[0]
            else:
                QJ.duanlian = QJ.duanlian_list[random.randint(0, len(QJ.duanlian_list) - 1)]

        text.insert(END, "未开启免登录模式,稍后开始登录!!!")
        text.update()
        text.see(END)
        QJ.ua_list_ = ua_list[random.randint(0, 28)]
        __headers_mobile['User-Agent'] = QJ.ua_list_
        text.insert(END, "定义浏览器移动端标识(User-Agent):" + QJ.ua_list_)
        text.update()
        text.see(END)
        text.insert(END, "当前选择的分享短链:" + QJ.duanlian)
        text.update()
        text.see(END)
        requests.adapters.DEFAULT_RETRIES = 5
        s = requests.session()
        s.keep_alive = False
        driver = webdriver.Chrome(executable_path="Google Chrome/chromedriver.exe")
        time.sleep(1)
        if var4.get() == 1:
            driver.maximize_window()
        time.sleep(3)
        driver.implicitly_wait(30)
        driver.get("https://live.kuaishou.com/v/hot/")
        file = '提示音.wav'  # 文件名是完整路径名
        iframes = driver.find_elements_by_tag_name("iframe")
        while iframes != []:
            pygame.mixer.init()  # 初始化音频
            track = pygame.mixer.music.load(file)  # 载入音乐文件
            pygame.mixer.music.play()  # 开始播放
            time.sleep(3)
            iframes = driver.find_elements_by_tag_name("iframe")
            if iframes != []:
                text.insert(END, "出现验证码弹窗请等待自动验证或者自动验证失败后在手动验证")
                text.update()
                text.see(END)
                iframe = driver.find_elements_by_tag_name("iframe")[0]
                driver.switch_to.default_content()
                driver.switch_to.frame(iframe)
                bgtu = driver.find_element_by_xpath('/html/body/div/div/div[1]/img[1]')
                bgtu_link = bgtu.get_attribute("src")
                # r = requests.get(bgtu_link, verify=False)
                while True:  # 一直循环，知道访问站点成功
                    try:
                        # 以下except都是用来捕获当requests请求出现异常时，
                        # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
                        requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
                        r = requests.get(bgtu_link, verify=False)
                        r.raise_for_status()
                        # res = requests.get(w_url, headers=__headers_mobile, verify=False)
                        # res.raise_for_status()
                        break
                    except requests.exceptions.HTTPError:
                        text.insert(END, "HTTPError, 等待5秒后再次下载!!!")
                        text.update()
                        text.see(END)
                        time.sleep(5)
                    except requests.exceptions.ConnectionError:
                        text.insert(END, "ConnectionError, 等待5秒后再次下载!!!")
                        text.update()
                        text.see(END)
                        time.sleep(5)
                    except requests.exceptions.ChunkedEncodingError:
                        text.insert(END, "ChunkedEncodingError, 等待5秒后再次下载!!!")
                        text.update()
                        text.see(END)
                        time.sleep(5)
                    except:
                        text.insert(END, "Unfortunitely -- An Unknow Error Happened, 等待60秒后程序重新运行!!!")
                        text.update()
                        text.see(END)
                        time.sleep(60)
                        restart_program()
                dir = "./"
                # if not os.path.exists(dir):
                #     os.makedirs(dir)
                bjtu_pic = dir + "2.png"
                with open(bjtu_pic, "wb") as f:
                    f.write(r.content)
                slidertu = driver.find_element_by_xpath('/html/body/div/div/div[1]/img[2]')
                slidertu_link = slidertu.get_attribute("src")
                # r = requests.get(slidertu_link, verify=False)
                while True:  # 一直循环，知道访问站点成功
                    try:
                        # 以下except都是用来捕获当requests请求出现异常时，
                        # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
                        requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
                        r = requests.get(slidertu_link, verify=False)
                        r.raise_for_status()
                        # res = requests.get(w_url, headers=__headers_mobile, verify=False)
                        # res.raise_for_status()
                        break
                    except requests.exceptions.HTTPError:
                        text.insert(END, "HTTPError, 等待5秒后再次下载!!!")
                        text.update()
                        text.see(END)
                        time.sleep(5)
                    except requests.exceptions.ConnectionError:
                        text.insert(END, "ConnectionError, 等待5秒后再次下载!!!")
                        text.update()
                        text.see(END)
                        time.sleep(5)
                    except requests.exceptions.ChunkedEncodingError:
                        text.insert(END, "ChunkedEncodingError, 等待5秒后再次下载!!!")
                        text.update()
                        text.see(END)
                        time.sleep(5)
                    except:
                        text.insert(END, "Unfortunitely -- An Unknow Error Happened, 等待60秒后程序重新运行!!!")
                        text.update()
                        text.see(END)
                        time.sleep(60)
                        restart_program()
                dir = "./"
                # if not os.path.exists(dir):
                #     os.makedirs(dir)
                slider_pic = dir + "1.png"
                with open(slider_pic, "wb") as f:
                    f.write(r.content)
                image_pyramid()
                image_contrast()
                huakuai = driver.find_element_by_xpath('/html/body/div/div/div[2]/div[2]/div/i')
                time.sleep(1)
                # move_to_gap(huakuai, get_track(340))
                ActionChains(driver).click_and_hold(huakuai).perform()
                for x in get_track(QJ.max_x * 4 - 25):
                    ActionChains(driver).move_by_offset(xoffset=x, yoffset=0).perform()
                time.sleep(0.5)
                ActionChains(driver).release().perform()
                time.sleep(5)
                driver.switch_to.default_content()
                time.sleep(1)
                # driver.refresh()
                pygame.mixer.music.stop()  # 停止播放
                iframes = driver.find_elements_by_tag_name("iframe")
                if iframes == []:
                    pygame.mixer.music.stop()  # 停止播放
                    break
                else:
                    driver.refresh()
        name = driver.find_element_by_xpath('//*[@id="app"]/div[1]/div[1]/header/div/div[2]/div[3]/a/span')
        name_title = name.get_attribute('title')
        # cookie= driver.get_cookies()
        while name_title == "":  # 这里刚刚修改
            text.insert(END, "你还没有登录,请登录!!!")
            text.update()
            text.see(END)
            if var5.get() == 1:
                time.sleep(1)
                driver.find_element_by_class_name("tip-container").click()
                time.sleep(1)
                driver.find_element_by_class_name("third-part-entry-qq").click()
                driver.close()
                time.sleep(3)
                driver.switch_to.window(driver.window_handles[0])
                file = '提示音.wav'  # 文件名是完整路径名
                driver.switch_to.frame(0)
                QQhaos = driver.find_elements_by_class_name("nick")
                shuaxincishu = 0
                if QQhaos == []:
                    QQhao = ""
                    driver.switch_to.default_content()
                else:
                    QQhao = str(QQhaos[0].text)
                    driver.switch_to.default_content()
                while QQhao == "":
                    if shuaxincishu == 3:
                        time.sleep(1)
                        driver.get("https://live.kuaishou.com/v/hot/")
                        shuaxincishu = 0
                        time.sleep(3)
                        time.sleep(1)
                        driver.find_element_by_class_name("tip-container").click()
                        time.sleep(1)
                        driver.find_element_by_class_name("third-part-entry-qq").click()
                        driver.close()
                        time.sleep(3)
                        driver.switch_to.window(driver.window_handles[0])
                        file = '提示音.wav'  # 文件名是完整路径名
                        driver.switch_to.frame(0)
                        QQhaos = driver.find_elements_by_class_name("nick")
                        shuaxincishu = 0
                        if QQhaos == []:
                            QQhao = ""
                            driver.switch_to.default_content()
                        else:
                            QQhao = str(QQhaos[0].text)
                            driver.switch_to.default_content()
                    pygame.mixer.init()  # 初始化音频
                    track = pygame.mixer.music.load(file)  # 载入音乐文件
                    pygame.mixer.music.play()  # 开始播放
                    time.sleep(3)
                    iframes = driver.find_elements_by_tag_name("iframe")
                    if QQhao == "":
                        text.insert(END, "出现验证码弹窗请等待自动验证或者自动验证失败后在手动验证")
                        text.update()
                        text.see(END)
                        iframe = driver.find_elements_by_tag_name("iframe")[0]
                        driver.switch_to.default_content()
                        driver.switch_to.frame(iframe)
                        bgtu = driver.find_element_by_xpath('/html/body/div/div/div[1]/img[1]')
                        bgtu_link = bgtu.get_attribute("src")
                        # r = requests.get(bgtu_link, verify=False)
                        while True:  # 一直循环，知道访问站点成功
                            try:
                                # 以下except都是用来捕获当requests请求出现异常时，
                                # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
                                requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
                                r = requests.get(bgtu_link, verify=False)
                                r.raise_for_status()
                                # res = requests.get(w_url, headers=__headers_mobile, verify=False)
                                # res.raise_for_status()
                                break
                            except requests.exceptions.HTTPError:
                                text.insert(END, "HTTPError, 等待5秒后再次下载!!!")
                                text.update()
                                text.see(END)
                                time.sleep(5)
                            except requests.exceptions.ConnectionError:
                                text.insert(END, "ConnectionError, 等待5秒后再次下载!!!")
                                text.update()
                                text.see(END)
                                time.sleep(5)
                            except requests.exceptions.ChunkedEncodingError:
                                text.insert(END, "ChunkedEncodingError, 等待5秒后再次下载!!!")
                                text.update()
                                text.see(END)
                                time.sleep(5)
                            except:
                                text.insert(END, "Unfortunitely -- An Unknow Error Happened, 等待60秒后程序重新运行!!!")
                                text.update()
                                text.see(END)
                                time.sleep(60)
                                restart_program()
                        dir = "./"
                        # if not os.path.exists(dir):
                        #     os.makedirs(dir)
                        bjtu_pic = dir + "2.png"
                        with open(bjtu_pic, "wb") as f:
                            f.write(r.content)
                        slidertu = driver.find_element_by_xpath('/html/body/div/div/div[1]/img[2]')
                        slidertu_link = slidertu.get_attribute("src")
                        # r = requests.get(slidertu_link, verify=False)
                        while True:  # 一直循环，知道访问站点成功
                            try:
                                # 以下except都是用来捕获当requests请求出现异常时，
                                # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
                                requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
                                r = requests.get(slidertu_link, verify=False)
                                r.raise_for_status()
                                # res = requests.get(w_url, headers=__headers_mobile, verify=False)
                                # res.raise_for_status()
                                break
                            except requests.exceptions.HTTPError:
                                text.insert(END, "HTTPError, 等待5秒后再次下载!!!")
                                text.update()
                                text.see(END)
                                time.sleep(5)
                            except requests.exceptions.ConnectionError:
                                text.insert(END, "ConnectionError, 等待5秒后再次下载!!!")
                                text.update()
                                text.see(END)
                                time.sleep(5)
                            except requests.exceptions.ChunkedEncodingError:
                                text.insert(END, "ChunkedEncodingError, 等待5秒后再次下载!!!")
                                text.update()
                                text.see(END)
                                time.sleep(5)
                            except:
                                text.insert(END, "Unfortunitely -- An Unknow Error Happened, 等待60秒后程序重新运行!!!")
                                text.update()
                                text.see(END)
                                time.sleep(60)
                                restart_program()
                        dir = "./"
                        # if not os.path.exists(dir):
                        #     os.makedirs(dir)
                        slider_pic = dir + "1.png"
                        with open(slider_pic, "wb") as f:
                            f.write(r.content)
                        image_pyramid()
                        image_contrast()
                        huakuai = driver.find_element_by_xpath('/html/body/div/div/div[2]/div[2]/div/i')
                        time.sleep(1)
                        # move_to_gap(huakuai, get_track(340))
                        ActionChains(driver).click_and_hold(huakuai).perform()
                        for x in get_track(QJ.max_x * 4 - 25):
                            ActionChains(driver).move_by_offset(xoffset=x, yoffset=0).perform()
                        time.sleep(0.5)
                        ActionChains(driver).release().perform()
                        time.sleep(5)
                        driver.switch_to.default_content()
                        time.sleep(1)
                        # driver.refresh()
                    pygame.mixer.music.stop()  # 停止播放
                    driver.switch_to.frame(0)
                    QQhaos = driver.find_elements_by_class_name("nick")
                    if QQhaos == []:
                        QQhao = ""
                        driver.switch_to.default_content()
                        driver.refresh()
                        shuaxincishu += 1
                    else:
                        QQhao = str(QQhaos[0].text)
                        driver.switch_to.default_content()
                        time.sleep(1)
                        pygame.mixer.music.stop()  # 停止播放
                        break
                driver.switch_to.frame(0)
                driver.implicitly_wait(30)
                driver.find_element_by_class_name("nick").click()
                time.sleep(3)
                driver.get("https://live.kuaishou.com/v/hot/")
                driver.implicitly_wait(30)
                name = driver.find_element_by_xpath(
                    '//*[@id="app"]/div[1]/div[1]/header/div/div[2]/div[3]/a/span')
                name_title = name.get_attribute('title')
            else:
                QQhao = ""
                pygame.mixer.init()  # 初始化音频
                track = pygame.mixer.music.load(file)  # 载入音乐文件
                pygame.mixer.music.play()  # 开始播放
                driver.find_element_by_class_name("tip-container").click()
                time.sleep(20)
                pygame.mixer.music.stop()  # 停止播放
                driver.get("https://live.kuaishou.com/v/hot/")
                name = driver.find_element_by_xpath(
                    '//*[@id="app"]/div[1]/div[1]/header/div/div[2]/div[3]/a/span')
                name_title = name.get_attribute('title')
                driver.refresh()
        text.delete(0, END)
        text.insert(END, "你已经登录,登录名:" + name_title)
        text.update()
        text.see(END)
        if QQhao != "":
            text.insert(END, "你登录的QQ号码:" + QQhao)
            text.update()
            text.see(END)
        else:
            text.insert(END, "你已经扫码登录")
            text.update()
            text.see(END)
        cookie = driver.get_cookies()
        # driver.get("https://live.kuaishou.com/u/G338217245/3xjz7rnjnh6hjts")
        cookie = [item['value'] for item in driver.get_cookies()]
        cookie1 = [item['name'] for item in driver.get_cookies()]
        # cookie = [item['name'] + '=' + item['value'] for item in driver.get_cookies()]
        for cookie_jici in range(len(cookie1)):
            if cookie1[cookie_jici] == "did":
                param_did = cookie[cookie_jici]
                break
        for cookie_jici2 in range(len(cookie1)):
            if cookie1[cookie_jici2] == "kuaishou.live.web_st":
                param_did2 = cookie[cookie_jici2]
                break
        for cookie_jici3 in range(len(cookie1)):
            if cookie1[cookie_jici3] == "kuaishou.live.web_ph":
                param_did3 = cookie[cookie_jici3]
                break
        for cookie_jici4 in range(len(cookie1)):
            if cookie1[cookie_jici4] == "kuaishou.live.bfb1s":
                param_did4 = cookie[cookie_jici4]
                break
        for cookie_jici5 in range(len(cookie1)):
            if cookie1[cookie_jici5] == "userId":
                param_did5 = cookie[cookie_jici5]
                QJ.userid_cook = cookie[cookie_jici5]
                break
        config = configparser.ConfigParser()
        config.read('.\\config.ini')
        if config.has_section('cookie') == False:
            config.add_section('cookie')

        config.set('cookie', 'did', str(param_did))
        config.set('cookie', 'kuaishou.live.web_st', str(param_did2))
        config.set('cookie', 'kuaishou.live.web_ph', str(param_did3))
        config.set('cookie', 'kuaishou.live.bfb1s', str(param_did4))
        config.set('cookie', 'userId', str(param_did5))

        o = open('.\\config.ini', 'w')
        config.write(o)
        o.close()  # 不要忘
        time.sleep(3)
        driver.implicitly_wait(30)
        driver.get("https://live.kuaishou.com/v/hot/")
        iframes = driver.find_elements_by_tag_name("iframe")
        while iframes != []:
            pygame.mixer.init()  # 初始化音频
            track = pygame.mixer.music.load(file)  # 载入音乐文件
            pygame.mixer.music.play()  # 开始播放
            time.sleep(3)
            iframes = driver.find_elements_by_tag_name("iframe")
            if iframes != []:
                text.insert(END, "出现验证码弹窗请等待自动验证或者自动验证失败后在手动验证")
                text.update()
                text.see(END)
                iframe = driver.find_elements_by_tag_name("iframe")[0]
                driver.switch_to.default_content()
                driver.switch_to.frame(iframe)
                bgtu = driver.find_element_by_xpath('/html/body/div/div/div[1]/img[1]')
                bgtu_link = bgtu.get_attribute("src")
                # r = requests.get(bgtu_link, verify=False)
                while True:  # 一直循环，知道访问站点成功
                    try:
                        # 以下except都是用来捕获当requests请求出现异常时，
                        # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
                        requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
                        r = requests.get(bgtu_link, verify=False)
                        r.raise_for_status()
                        # res = requests.get(w_url, headers=__headers_mobile, verify=False)
                        # res.raise_for_status()
                        break
                    except requests.exceptions.HTTPError:
                        text.insert(END, "HTTPError, 等待5秒后再次下载!!!")
                        text.update()
                        text.see(END)
                        time.sleep(5)
                    except requests.exceptions.ConnectionError:
                        text.insert(END, "ConnectionError, 等待5秒后再次下载!!!")
                        text.update()
                        text.see(END)
                        time.sleep(5)
                    except requests.exceptions.ChunkedEncodingError:
                        text.insert(END, "ChunkedEncodingError, 等待5秒后再次下载!!!")
                        text.update()
                        text.see(END)
                        time.sleep(5)
                    except:
                        text.insert(END, "Unfortunitely -- An Unknow Error Happened, 等待60秒后程序重新运行!!!")
                        text.update()
                        text.see(END)
                        time.sleep(60)
                        restart_program()
                dir = "./"
                # if not os.path.exists(dir):
                #     os.makedirs(dir)
                bjtu_pic = dir + "2.png"
                with open(bjtu_pic, "wb") as f:
                    f.write(r.content)
                slidertu = driver.find_element_by_xpath('/html/body/div/div/div[1]/img[2]')
                slidertu_link = slidertu.get_attribute("src")
                # r = requests.get(slidertu_link, verify=False)
                while True:  # 一直循环，知道访问站点成功
                    try:
                        # 以下except都是用来捕获当requests请求出现异常时，
                        # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
                        requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
                        r = requests.get(slidertu_link, verify=False)
                        r.raise_for_status()
                        # res = requests.get(w_url, headers=__headers_mobile, verify=False)
                        # res.raise_for_status()
                        break
                    except requests.exceptions.HTTPError:
                        text.insert(END, "HTTPError, 等待5秒后再次下载!!!")
                        text.update()
                        text.see(END)
                        time.sleep(5)
                    except requests.exceptions.ConnectionError:
                        text.insert(END, "ConnectionError, 等待5秒后再次下载!!!")
                        text.update()
                        text.see(END)
                        time.sleep(5)
                    except requests.exceptions.ChunkedEncodingError:
                        text.insert(END, "ChunkedEncodingError, 等待5秒后再次下载!!!")
                        text.update()
                        text.see(END)
                        time.sleep(5)
                    except:
                        text.insert(END, "Unfortunitely -- An Unknow Error Happened, 等待60秒后程序重新运行!!!")
                        text.update()
                        text.see(END)
                        time.sleep(60)
                        restart_program()
                dir = "./"
                # if not os.path.exists(dir):
                #     os.makedirs(dir)
                slider_pic = dir + "1.png"
                with open(slider_pic, "wb") as f:
                    f.write(r.content)
                image_pyramid()
                image_contrast()
                huakuai = driver.find_element_by_xpath('/html/body/div/div/div[2]/div[2]/div/i')
                time.sleep(1)
                # move_to_gap(huakuai, get_track(340))
                ActionChains(driver).click_and_hold(huakuai).perform()
                for x in get_track(QJ.max_x * 4 - 25):
                    ActionChains(driver).move_by_offset(xoffset=x, yoffset=0).perform()
                time.sleep(0.5)
                ActionChains(driver).release().perform()
                time.sleep(5)
                driver.switch_to.default_content()
                time.sleep(1)
                # driver.refresh()
                pygame.mixer.music.stop()  # 停止播放
                iframes = driver.find_elements_by_tag_name("iframe")
                if iframes == []:
                    pygame.mixer.music.stop()  # 停止播放
                    break
                else:
                    driver.refresh()
        driver.close()
        set_did(param_did, param_did2, param_did3, param_did4, param_did5)
    else:
        text.insert(END, "已开启免登录模式,稍后判断cookie是否存在!!!")
        text.update()
        text.see(END)
        if QJ.cookie1 == "" and QJ.cookie2 == "" and QJ.cookie3 == "" and QJ.cookie4 == "" and QJ.cookie5 == "":
            if QJ.duanlian_list[0] == "":
                text.insert(END, "请在config.ini配置文件中填入分享短链!!!")
                text.update()
                text.see(END)
                time.sleep(5)
                root.quit()
            else:
                if len(QJ.duanlian_list) == 1:
                    QJ.duanlian = QJ.duanlian_list[0]
                else:
                    QJ.duanlian = QJ.duanlian_list[random.randint(0, len(QJ.duanlian_list) - 1)]

            text.insert(END, "cookie不存在,稍后开始登录!!!")
            text.update()
            text.see(END)
            QJ.ua_list_ = ua_list[random.randint(0, 28)]
            __headers_mobile['User-Agent'] = QJ.ua_list_
            text.insert(END, "定义浏览器移动端标识(User-Agent):" + QJ.ua_list_)
            text.update()
            text.see(END)
            text.insert(END, "当前选择的分享短链:" + QJ.duanlian)
            text.update()
            text.see(END)
            requests.adapters.DEFAULT_RETRIES = 5
            s = requests.session()
            s.keep_alive = False
            driver = webdriver.Chrome(executable_path="Google Chrome/chromedriver.exe")
            time.sleep(1)
            if var4.get() == 1:
                driver.maximize_window()
            time.sleep(3)
            driver.implicitly_wait(30)
            driver.get("https://live.kuaishou.com/v/hot/")
            file = '提示音.wav'  # 文件名是完整路径名
            iframes = driver.find_elements_by_tag_name("iframe")
            while iframes != []:
                pygame.mixer.init()  # 初始化音频
                track = pygame.mixer.music.load(file)  # 载入音乐文件
                pygame.mixer.music.play()  # 开始播放
                time.sleep(3)
                iframes = driver.find_elements_by_tag_name("iframe")
                if iframes != []:
                    text.insert(END, "出现验证码弹窗请等待自动验证或者自动验证失败后在手动验证")
                    text.update()
                    text.see(END)
                    iframe = driver.find_elements_by_tag_name("iframe")[0]
                    driver.switch_to.default_content()
                    driver.switch_to.frame(iframe)
                    bgtu = driver.find_element_by_xpath('/html/body/div/div/div[1]/img[1]')
                    bgtu_link = bgtu.get_attribute("src")
                    # r = requests.get(bgtu_link, verify=False)
                    while True:  # 一直循环，知道访问站点成功
                        try:
                            # 以下except都是用来捕获当requests请求出现异常时，
                            # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
                            requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
                            r = requests.get(bgtu_link, verify=False)
                            r.raise_for_status()
                            # res = requests.get(w_url, headers=__headers_mobile, verify=False)
                            # res.raise_for_status()
                            break
                        except requests.exceptions.HTTPError:
                            text.insert(END, "HTTPError, 等待5秒后再次下载!!!")
                            text.update()
                            text.see(END)
                            time.sleep(5)
                        except requests.exceptions.ConnectionError:
                            text.insert(END, "ConnectionError, 等待5秒后再次下载!!!")
                            text.update()
                            text.see(END)
                            time.sleep(5)
                        except requests.exceptions.ChunkedEncodingError:
                            text.insert(END, "ChunkedEncodingError, 等待5秒后再次下载!!!")
                            text.update()
                            text.see(END)
                            time.sleep(5)
                        except:
                            text.insert(END, "Unfortunitely -- An Unknow Error Happened, 等待60秒后程序重新运行!!!")
                            text.update()
                            text.see(END)
                            time.sleep(60)
                            restart_program()
                    dir = "./"
                    # if not os.path.exists(dir):
                    #     os.makedirs(dir)
                    bjtu_pic = dir + "2.png"
                    with open(bjtu_pic, "wb") as f:
                        f.write(r.content)
                    slidertu = driver.find_element_by_xpath('/html/body/div/div/div[1]/img[2]')
                    slidertu_link = slidertu.get_attribute("src")
                    # r = requests.get(slidertu_link, verify=False)
                    while True:  # 一直循环，知道访问站点成功
                        try:
                            # 以下except都是用来捕获当requests请求出现异常时，
                            # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
                            requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
                            r = requests.get(slidertu_link, verify=False)
                            r.raise_for_status()
                            # res = requests.get(w_url, headers=__headers_mobile, verify=False)
                            # res.raise_for_status()
                            break
                        except requests.exceptions.HTTPError:
                            text.insert(END, "HTTPError, 等待5秒后再次下载!!!")
                            text.update()
                            text.see(END)
                            time.sleep(5)
                        except requests.exceptions.ConnectionError:
                            text.insert(END, "ConnectionError, 等待5秒后再次下载!!!")
                            text.update()
                            text.see(END)
                            time.sleep(5)
                        except requests.exceptions.ChunkedEncodingError:
                            text.insert(END, "ChunkedEncodingError, 等待5秒后再次下载!!!")
                            text.update()
                            text.see(END)
                            time.sleep(5)
                        except:
                            text.insert(END, "Unfortunitely -- An Unknow Error Happened, 等待60秒后程序重新运行!!!")
                            text.update()
                            text.see(END)
                            time.sleep(60)
                            restart_program()
                    dir = "./"
                    # if not os.path.exists(dir):
                    #     os.makedirs(dir)
                    slider_pic = dir + "1.png"
                    with open(slider_pic, "wb") as f:
                        f.write(r.content)
                    image_pyramid()
                    image_contrast()
                    huakuai = driver.find_element_by_xpath('/html/body/div/div/div[2]/div[2]/div/i')
                    time.sleep(1)
                    # move_to_gap(huakuai, get_track(340))
                    ActionChains(driver).click_and_hold(huakuai).perform()
                    for x in get_track(QJ.max_x * 4 - 25):
                        ActionChains(driver).move_by_offset(xoffset=x, yoffset=0).perform()
                    time.sleep(0.5)
                    ActionChains(driver).release().perform()
                    time.sleep(5)
                    driver.switch_to.default_content()
                    time.sleep(1)
                    # driver.refresh()
                    pygame.mixer.music.stop()  # 停止播放
                    iframes = driver.find_elements_by_tag_name("iframe")
                    if iframes == []:
                        pygame.mixer.music.stop()  # 停止播放
                        break
                    else:
                        driver.refresh()
            driver.get("https://live.kuaishou.com/v/hot/")
            name = driver.find_element_by_xpath('//*[@id="app"]/div[1]/div[1]/header/div/div[2]/div[3]/a/span')
            name_title = name.get_attribute('title')
            # cookie= driver.get_cookies()
            while name_title == "":  # 这里刚刚修改
                text.insert(END, "你还没有登录,请登录!!!")
                text.update()
                text.see(END)
                if var5.get() == 1:
                    time.sleep(1)
                    driver.find_element_by_class_name("tip-container").click()
                    time.sleep(1)
                    driver.find_element_by_class_name("third-part-entry-qq").click()
                    driver.close()
                    time.sleep(3)
                    driver.switch_to.window(driver.window_handles[0])
                    file = '提示音.wav'  # 文件名是完整路径名
                    driver.switch_to.frame(0)
                    QQhaos = driver.find_elements_by_class_name("nick")
                    shuaxincishu = 0
                    if QQhaos == []:
                        QQhao = ""
                        driver.switch_to.default_content()
                    else:
                        QQhao = str(QQhaos[0].text)
                        driver.switch_to.default_content()
                    while QQhao == "":
                        if shuaxincishu == 3:
                            time.sleep(1)
                            driver.get("https://live.kuaishou.com/v/hot/")
                            shuaxincishu = 0
                            time.sleep(3)
                            time.sleep(1)
                            driver.find_element_by_class_name("tip-container").click()
                            time.sleep(1)
                            driver.find_element_by_class_name("third-part-entry-qq").click()
                            driver.close()
                            time.sleep(3)
                            driver.switch_to.window(driver.window_handles[0])
                            file = '提示音.wav'  # 文件名是完整路径名
                            driver.switch_to.frame(0)
                            QQhaos = driver.find_elements_by_class_name("nick")
                            shuaxincishu = 0
                            if QQhaos == []:
                                QQhao = ""
                                driver.switch_to.default_content()
                            else:
                                QQhao = str(QQhaos[0].text)
                                driver.switch_to.default_content()
                        pygame.mixer.init()  # 初始化音频
                        track = pygame.mixer.music.load(file)  # 载入音乐文件
                        pygame.mixer.music.play()  # 开始播放
                        time.sleep(3)
                        iframes = driver.find_elements_by_tag_name("iframe")
                        if QQhao == "":
                            text.insert(END, "出现验证码弹窗请等待自动验证或者自动验证失败后在手动验证")
                            text.update()
                            text.see(END)
                            iframe = driver.find_elements_by_tag_name("iframe")[0]
                            driver.switch_to.default_content()
                            driver.switch_to.frame(iframe)
                            bgtu = driver.find_element_by_xpath('/html/body/div/div/div[1]/img[1]')
                            bgtu_link = bgtu.get_attribute("src")
                            # r = requests.get(bgtu_link, verify=False)
                            while True:  # 一直循环，知道访问站点成功
                                try:
                                    # 以下except都是用来捕获当requests请求出现异常时，
                                    # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
                                    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
                                    r = requests.get(bgtu_link, verify=False)
                                    r.raise_for_status()
                                    # res = requests.get(w_url, headers=__headers_mobile, verify=False)
                                    # res.raise_for_status()
                                    break
                                except requests.exceptions.HTTPError:
                                    text.insert(END, "HTTPError, 等待5秒后再次下载!!!")
                                    text.update()
                                    text.see(END)
                                    time.sleep(5)
                                except requests.exceptions.ConnectionError:
                                    text.insert(END, "ConnectionError, 等待5秒后再次下载!!!")
                                    text.update()
                                    text.see(END)
                                    time.sleep(5)
                                except requests.exceptions.ChunkedEncodingError:
                                    text.insert(END, "ChunkedEncodingError, 等待5秒后再次下载!!!")
                                    text.update()
                                    text.see(END)
                                    time.sleep(5)
                                except:
                                    text.insert(END, "Unfortunitely -- An Unknow Error Happened, 等待60秒后程序重新运行!!!")
                                    text.update()
                                    text.see(END)
                                    time.sleep(60)
                                    restart_program()
                            dir = "./"
                            # if not os.path.exists(dir):
                            #     os.makedirs(dir)
                            bjtu_pic = dir + "2.png"
                            with open(bjtu_pic, "wb") as f:
                                f.write(r.content)
                            slidertu = driver.find_element_by_xpath('/html/body/div/div/div[1]/img[2]')
                            slidertu_link = slidertu.get_attribute("src")
                            # r = requests.get(slidertu_link, verify=False)
                            while True:  # 一直循环，知道访问站点成功
                                try:
                                    # 以下except都是用来捕获当requests请求出现异常时，
                                    # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
                                    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
                                    r = requests.get(slidertu_link, verify=False)
                                    r.raise_for_status()
                                    # res = requests.get(w_url, headers=__headers_mobile, verify=False)
                                    # res.raise_for_status()
                                    break
                                except requests.exceptions.HTTPError:
                                    text.insert(END, "HTTPError, 等待5秒后再次下载!!!")
                                    text.update()
                                    text.see(END)
                                    time.sleep(5)
                                except requests.exceptions.ConnectionError:
                                    text.insert(END, "ConnectionError, 等待5秒后再次下载!!!")
                                    text.update()
                                    text.see(END)
                                    time.sleep(5)
                                except requests.exceptions.ChunkedEncodingError:
                                    text.insert(END, "ChunkedEncodingError, 等待5秒后再次下载!!!")
                                    text.update()
                                    text.see(END)
                                    time.sleep(5)
                                except:
                                    text.insert(END, "Unfortunitely -- An Unknow Error Happened, 等待60秒后程序重新运行!!!")
                                    text.update()
                                    text.see(END)
                                    time.sleep(60)
                                    restart_program()
                            dir = "./"
                            # if not os.path.exists(dir):
                            #     os.makedirs(dir)
                            slider_pic = dir + "1.png"
                            with open(slider_pic, "wb") as f:
                                f.write(r.content)
                            image_pyramid()
                            image_contrast()
                            huakuai = driver.find_element_by_xpath('/html/body/div/div/div[2]/div[2]/div/i')
                            time.sleep(1)
                            # move_to_gap(huakuai, get_track(340))
                            ActionChains(driver).click_and_hold(huakuai).perform()
                            for x in get_track(QJ.max_x * 4 - 25):
                                ActionChains(driver).move_by_offset(xoffset=x, yoffset=0).perform()
                            time.sleep(0.5)
                            ActionChains(driver).release().perform()
                            time.sleep(5)
                            driver.switch_to.default_content()
                            time.sleep(1)
                            # driver.refresh()
                        pygame.mixer.music.stop()  # 停止播放
                        driver.switch_to.frame(0)
                        QQhaos = driver.find_elements_by_class_name("nick")
                        if QQhaos == []:
                            QQhao = ""
                            driver.switch_to.default_content()
                            driver.refresh()
                            shuaxincishu += 1
                        else:
                            QQhao = str(QQhaos[0].text)
                            driver.switch_to.default_content()
                            time.sleep(1)
                            pygame.mixer.music.stop()  # 停止播放
                            break
                    driver.switch_to.frame(0)
                    driver.implicitly_wait(30)
                    driver.find_element_by_class_name("nick").click()
                    time.sleep(3)
                    driver.get("https://live.kuaishou.com/v/hot/")
                    driver.implicitly_wait(30)
                    name = driver.find_element_by_xpath(
                        '//*[@id="app"]/div[1]/div[1]/header/div/div[2]/div[3]/a/span')
                    name_title = name.get_attribute('title')
                else:
                    QQhao = ""
                    pygame.mixer.init()  # 初始化音频
                    track = pygame.mixer.music.load(file)  # 载入音乐文件
                    pygame.mixer.music.play()  # 开始播放
                    driver.find_element_by_class_name("tip-container").click()
                    time.sleep(20)
                    pygame.mixer.music.stop()  # 停止播放
                    driver.get("https://live.kuaishou.com/v/hot/")
                    name = driver.find_element_by_xpath(
                        '//*[@id="app"]/div[1]/div[1]/header/div/div[2]/div[3]/a/span')
                    name_title = name.get_attribute('title')
                    driver.refresh()
            text.delete(0, END)
            text.insert(END, "你已经登录,登录名:" + name_title)
            text.update()
            text.see(END)
            if QQhao != "":
                text.insert(END, "你登录的QQ号码:" + QQhao)
                text.update()
                text.see(END)
            else:
                text.insert(END, "你已经扫码登录")
                text.update()
                text.see(END)
            cookie = driver.get_cookies()
            # driver.get("https://live.kuaishou.com/u/G338217245/3xjz7rnjnh6hjts")
            cookie = [item['value'] for item in driver.get_cookies()]
            cookie1 = [item['name'] for item in driver.get_cookies()]
            # cookie = [item['name'] + '=' + item['value'] for item in driver.get_cookies()]
            for cookie_jici in range(len(cookie1)):
                if cookie1[cookie_jici] == "did":
                    param_did = cookie[cookie_jici]
                    break
            for cookie_jici2 in range(len(cookie1)):
                if cookie1[cookie_jici2] == "kuaishou.live.web_st":
                    param_did2 = cookie[cookie_jici2]
                    break
            for cookie_jici3 in range(len(cookie1)):
                if cookie1[cookie_jici3] == "kuaishou.live.web_ph":
                    param_did3 = cookie[cookie_jici3]
                    break
            for cookie_jici4 in range(len(cookie1)):
                if cookie1[cookie_jici4] == "kuaishou.live.bfb1s":
                    param_did4 = cookie[cookie_jici4]
                    break
            for cookie_jici5 in range(len(cookie1)):
                if cookie1[cookie_jici5] == "userId":
                    param_did5 = cookie[cookie_jici5]
                    QJ.userid_cook = cookie[cookie_jici5]
                    break
            config = configparser.ConfigParser()
            config.read('.\\config.ini')
            if config.has_section('cookie') == False:
                config.add_section('cookie')

            config.set('cookie', 'did', str(param_did))
            config.set('cookie', 'kuaishou.live.web_st', str(param_did2))
            config.set('cookie', 'kuaishou.live.web_ph', str(param_did3))
            config.set('cookie', 'kuaishou.live.bfb1s', str(param_did4))
            config.set('cookie', 'userId', str(param_did5))

            o = open('.\\config.ini', 'w')
            config.write(o)
            o.close()  # 不要忘
            time.sleep(3)
            driver.implicitly_wait(30)
            driver.get("https://live.kuaishou.com/v/hot/")
            iframes = driver.find_elements_by_tag_name("iframe")
            while iframes != []:
                pygame.mixer.init()  # 初始化音频
                track = pygame.mixer.music.load(file)  # 载入音乐文件
                pygame.mixer.music.play()  # 开始播放
                time.sleep(3)
                iframes = driver.find_elements_by_tag_name("iframe")
                if iframes != []:
                    text.insert(END, "出现验证码弹窗请等待自动验证或者自动验证失败后在手动验证")
                    text.update()
                    text.see(END)
                    iframe = driver.find_elements_by_tag_name("iframe")[0]
                    driver.switch_to.default_content()
                    driver.switch_to.frame(iframe)
                    bgtu = driver.find_element_by_xpath('/html/body/div/div/div[1]/img[1]')
                    bgtu_link = bgtu.get_attribute("src")
                    # r = requests.get(bgtu_link, verify=False)
                    while True:  # 一直循环，知道访问站点成功
                        try:
                            # 以下except都是用来捕获当requests请求出现异常时，
                            # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
                            requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
                            r = requests.get(bgtu_link, verify=False)
                            r.raise_for_status()
                            # res = requests.get(w_url, headers=__headers_mobile, verify=False)
                            # res.raise_for_status()
                            break
                        except requests.exceptions.HTTPError:
                            text.insert(END, "HTTPError, 等待5秒后再次下载!!!")
                            text.update()
                            text.see(END)
                            time.sleep(5)
                        except requests.exceptions.ConnectionError:
                            text.insert(END, "ConnectionError, 等待5秒后再次下载!!!")
                            text.update()
                            text.see(END)
                            time.sleep(5)
                        except requests.exceptions.ChunkedEncodingError:
                            text.insert(END, "ChunkedEncodingError, 等待5秒后再次下载!!!")
                            text.update()
                            text.see(END)
                            time.sleep(5)
                        except:
                            text.insert(END, "Unfortunitely -- An Unknow Error Happened, 等待60秒后程序重新运行!!!")
                            text.update()
                            text.see(END)
                            time.sleep(60)
                            restart_program()
                    dir = "./"
                    # if not os.path.exists(dir):
                    #     os.makedirs(dir)
                    bjtu_pic = dir + "2.png"
                    with open(bjtu_pic, "wb") as f:
                        f.write(r.content)
                    slidertu = driver.find_element_by_xpath('/html/body/div/div/div[1]/img[2]')
                    slidertu_link = slidertu.get_attribute("src")
                    # r = requests.get(slidertu_link, verify=False)
                    while True:  # 一直循环，知道访问站点成功
                        try:
                            # 以下except都是用来捕获当requests请求出现异常时，
                            # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
                            requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
                            r = requests.get(slidertu_link, verify=False)
                            r.raise_for_status()
                            # res = requests.get(w_url, headers=__headers_mobile, verify=False)
                            # res.raise_for_status()
                            break
                        except requests.exceptions.HTTPError:
                            text.insert(END, "HTTPError, 等待5秒后再次下载!!!")
                            text.update()
                            text.see(END)
                            time.sleep(5)
                        except requests.exceptions.ConnectionError:
                            text.insert(END, "ConnectionError, 等待5秒后再次下载!!!")
                            text.update()
                            text.see(END)
                            time.sleep(5)
                        except requests.exceptions.ChunkedEncodingError:
                            text.insert(END, "ChunkedEncodingError, 等待5秒后再次下载!!!")
                            text.update()
                            text.see(END)
                            time.sleep(5)
                        except:
                            text.insert(END, "Unfortunitely -- An Unknow Error Happened, 等待60秒后程序重新运行!!!")
                            text.update()
                            text.see(END)
                            time.sleep(60)
                            restart_program()
                    dir = "./"
                    # if not os.path.exists(dir):
                    #     os.makedirs(dir)
                    slider_pic = dir + "1.png"
                    with open(slider_pic, "wb") as f:
                        f.write(r.content)
                    image_pyramid()
                    image_contrast()
                    huakuai = driver.find_element_by_xpath('/html/body/div/div/div[2]/div[2]/div/i')
                    time.sleep(1)
                    # move_to_gap(huakuai, get_track(340))
                    ActionChains(driver).click_and_hold(huakuai).perform()
                    for x in get_track(QJ.max_x * 4 - 25):
                        ActionChains(driver).move_by_offset(xoffset=x, yoffset=0).perform()
                    time.sleep(0.5)
                    ActionChains(driver).release().perform()
                    time.sleep(5)
                    driver.switch_to.default_content()
                    time.sleep(1)
                    # driver.refresh()
                    pygame.mixer.music.stop()  # 停止播放
                    iframes = driver.find_elements_by_tag_name("iframe")
                    if iframes == []:
                        pygame.mixer.music.stop()  # 停止播放
                        break
                    else:
                        driver.refresh()
            driver.close()
            set_did(param_did, param_did2, param_did3, param_did4, param_did5)
        else:
            if QJ.duanlian_list[0] == "":
                text.insert(END, "请在config.ini配置文件中填入分享短链!!!")
                text.update()
                text.see(END)
                time.sleep(5)
                root.quit()
            else:
                if len(QJ.duanlian_list) == 1:
                    QJ.duanlian = QJ.duanlian_list[0]
                else:
                    QJ.duanlian = QJ.duanlian_list[random.randint(0, len(QJ.duanlian_list) - 1)]

            text.insert(END, "cookie存在,无需登录!!!")
            text.update()
            text.see(END)
            QJ.ua_list_ = ua_list[random.randint(0, 28)]
            __headers_mobile['User-Agent'] = QJ.ua_list_
            text.insert(END, "定义浏览器移动端标识(User-Agent):" + QJ.ua_list_)
            text.update()
            text.see(END)
            text.insert(END, "当前选择的分享短链:" + QJ.duanlian)
            text.update()
            text.see(END)
            requests.adapters.DEFAULT_RETRIES = 5
            s = requests.session()
            s.keep_alive = False
            param_did = QJ.cookie1
            param_did2 = QJ.cookie2
            param_did3 = QJ.cookie3
            param_did4 = QJ.cookie4
            param_did5 = QJ.cookie5
            set_did(param_did, param_did2, param_did3, param_did4, param_did5)


def restart_program():  # 重启程序
    if QJ.zhuangtaima != "":
        loginout()
        python = sys.executable
        os.execl(python, python, *sys.argv)
    else:
        python = sys.executable
        os.execl(python, python, *sys.argv)



def __intro():
    thread_it(__openchrome,)

def __intro2():
    thread_it(login,)

def thread_it(func, *args):
    '''将函数打包进线程'''
    # 创建
    t = threading.Thread(target=func, args=args)
    # 守护 !!!
    t.setDaemon(True)
    # 启动
    t.start()
    # 阻塞--卡死界面！
    # t.join()

def qccookie():
    text.insert(END, "正在清除cookie,3秒后重启启动软件!!!")
    text.update()
    text.see(END)
    time.sleep(1)
    config = configparser.ConfigParser()
    config.read('.\\config.ini')
    if config.has_section('cookie') == False:
        config.add_section('cookie')

    config.set('cookie', 'did', "")
    config.set('cookie', 'kuaishou.live.web_st', "")
    config.set('cookie', 'kuaishou.live.web_ph', "")
    config.set('cookie', 'kuaishou.live.bfb1s', "")
    config.set('cookie', 'userId', "")

    o = open('.\\config.ini', 'w')
    config.write(o)
    o.close()  # 不要忘

    text.insert(END, "3秒后重启软件!!!")
    text.update()
    text.see(END)
    time.sleep(1)
    text.insert(END, "2秒后重启软件!!!")
    text.update()
    text.see(END)
    time.sleep(1)
    text.insert(END, "1秒后重启软件!!!")
    text.update()
    text.see(END)
    time.sleep(1)
    restart_program()

def one_click_access():
    global click_access
    click_access = 1
    thread_it(__init__, )


def one_click_access2():
    page = 1
    if not os.path.exists("uid.txt"):
        open("uid.txt", "w")
    payload = {"operationName": "FollowQuery",
               "variables": {"count": 999,"pcursor":""},
               "query": "query FollowQuery($pcursor: String, $count: Int) {\n  allFollows(pcursor: $pcursor, count: $count) {\n    list {\n      id\n      name\n      living\n      avatar\n      sex\n      description\n      counts {\n        fan\n        follow\n        photo\n        __typename\n      }\n      __typename\n    }\n    pcursor\n    __typename\n  }\n}\n"}
    # payload = {"operationName": "privateFeedsQuery",
    #            "variables":{"principalId":uid,"pcursor":"","count":99999},
    #            "query": "query privateFeedsQuery($principalId: String, $pcursor: String, $count: Int) {\n  privateFeeds(principalId: $principalId, pcursor: $pcursor, count: $count) {\n    pcursor\n    list {\n      id\n      thumbnailUrl\n      poster\n      workType\n      type\n      useVideoPlayer\n      imgUrls\n      imgSizes\n      magicFace\n      musicName\n      caption\n      location\n      liked\n      onlyFollowerCanComment\n      relativeHeight\n      timestamp\n      width\n      height\n      counts {\n        displayView\n        displayLike\n        displayComment\n        __typename\n      }\n      user {\n        id\n        eid\n        name\n        avatar\n        __typename\n      }\n      expTag\n      __typename\n    }\n    __typename\n  }\n}\n"}
    res = requests.post(DATA_URL, headers=__headers_web, json=payload)

    works = json.loads(res.content.decode(encoding='utf-8', errors='strict'))['data']['allFollows']['list']
    pcursor = json.loads(res.content.decode(encoding='utf-8', errors='strict'))['data']['allFollows']['pcursor']
    text.insert(END, '第%s页uid获取成功\n' % (page))
    text.update()
    text.see(END)

    page += 1
    payload = {"operationName": "FollowQuery",
               "variables": {"count": 999, "pcursor": 1017},
               "query": "query FollowQuery($pcursor: String, $count: Int) {\n  allFollows(pcursor: $pcursor, count: $count) {\n    list {\n      id\n      name\n      living\n      avatar\n      sex\n      description\n      counts {\n        fan\n        follow\n        photo\n        __typename\n      }\n      __typename\n    }\n    pcursor\n    __typename\n  }\n}\n"}
    # payload = {"operationName": "privateFeedsQuery",
    #            "variables":{"principalId":uid,"pcursor":"","count":99999},
    #            "query": "query privateFeedsQuery($principalId: String, $pcursor: String, $count: Int) {\n  privateFeeds(principalId: $principalId, pcursor: $pcursor, count: $count) {\n    pcursor\n    list {\n      id\n      thumbnailUrl\n      poster\n      workType\n      type\n      useVideoPlayer\n      imgUrls\n      imgSizes\n      magicFace\n      musicName\n      caption\n      location\n      liked\n      onlyFollowerCanComment\n      relativeHeight\n      timestamp\n      width\n      height\n      counts {\n        displayView\n        displayLike\n        displayComment\n        __typename\n      }\n      user {\n        id\n        eid\n        name\n        avatar\n        __typename\n      }\n      expTag\n      __typename\n    }\n    __typename\n  }\n}\n"}
    res1 = requests.post(DATA_URL, headers=__headers_web, json=payload)
    works = works + json.loads(res1.content.decode(encoding='utf-8', errors='strict'))['data']['allFollows']['list']
    pcursor = json.loads(res.content.decode(encoding='utf-8', errors='strict'))['data']['allFollows']['pcursor']
    text.insert(END, '第%s页uid获取成功\n' % (page))
    text.update()
    text.see(END)


    works_uid = works
    gz_list = len(works_uid)
    gz_text = open("uid.txt", "w+")
    gz_text.truncate(0)
    text.insert(END, "正在获取uid中,请稍等..." )
    text.update()
    text.see(END)
    for gz in range(len(works_uid)):
        gz_text.write(str(works_uid[gz]['id']) + "\n")
    gz_text.close()
    text.insert(END, "获取并写入uid.txt成功..." )
    text.update()
    text.see(END)
    new_down = tkinter.messagebox.askokcancel('提示', '你是否要重新开始从头下载!!!')
    if new_down == True:
        save_config_jb3()
    else:
        tkinter.messagebox.showinfo('提示', '看来你不愿意重新重头开始下载!')

def stop():
    """Stop scanning by setting the global flag to False."""
    QJ.stop = True
    text.insert(END, "正在跳过当前用户...")
    text.update()
    text.see(END)

def save_config_jb():
    config = configparser.ConfigParser()
    config.read('.\\config.ini')
    if config.has_section('基本设置') == False:
        config.add_section('基本设置')


    config.set('基本设置','自动模式',str(var2.get()))
    config.set('基本设置', '免登录', str(var8.get()))
    config.set('基本设置','延时',entry.get())
    config.set('基本设置', '已存在次数', entry2.get())
    config.set('基本设置', '自动跳过', str(var.get()))
    config.set('基本设置', '浏览器最大化', str(var4.get()))
    config.set('基本设置', '使用QQ登录', str(var5.get()))
    config.set('基本设置', '只下载视频', str(var7.get()))
    config.set('基本设置', '只下载图集', str(var3.get()))
    config.set('基本设置', '老版本参数', str(var9.get()))
    config.set('基本设置', '参数版本自动判断', str(var10.get()))

    # config.set('基本设置', '单卡卡密自动登录', str(var6.get()))
    # config.set('基本设置', '单卡卡密', dkkmbjk.get())


    o = open('.\\config.ini', 'w')
    config.write(o)
    o.close()  # 不要忘记关闭
    tkinter.messagebox.showinfo('提示', '保存配置后软件自动重启!!!')
    time.sleep(1)
    restart_program()


def save_config_jb2():
    config = configparser.ConfigParser()
    config.read('.\\config.ini')
    if config.has_section('用户日志') == False:
        config.add_section('用户日志')

    config.set('用户日志', '当前uid', QJ.current_uid)
    config.set('用户日志', '当前解析视频数', str(QJ.video_num))

    o = open('.\\config.ini', 'w')
    config.write(o)
    o.close()  # 不要忘记关闭


def save_config_jb3():
    config = configparser.ConfigParser()
    config.read('.\\config.ini')
    if config.has_section('用户日志') == False:
        config.add_section('用户日志')

    config.set('用户日志', '当前uid', "0")
    config.set('用户日志', '当前解析视频数', "0")

    o = open('.\\config.ini', 'w')
    config.write(o)
    o.close()  # 不要忘记关闭
    tkinter.messagebox.showinfo('提示', '保存配置后软件自动重启!!!')
    time.sleep(1)
    restart_program()

def save_config_jb4():
    config = configparser.ConfigParser()
    config.read('.\\config.ini')
    if config.has_section('用户日志') == False:
        config.add_section('用户日志')

    config.set('用户日志', '当前解析视频数', "0")

    o = open('.\\config.ini', 'w')
    config.write(o)
    o.close()  # 不要忘记关闭
    tkinter.messagebox.showinfo('提示', '保存配置后软件自动重启!!!')
    time.sleep(1)
    restart_program()

def login():
    if dkkmbjk.get() != "":
        QJ.dkkm = dkkmbjk.get()
        QJ.jiqima = jiqimabjk.get()
        payload = {"SingleCode": QJ.dkkm,
                   "Ver": "1.0",
                   "Mac": QJ.jiqima}
        #res = requests.post("http://w.eydata.net/521270375f95bba8", payload, verify=False)
        while True:  # 一直循环，知道访问站点成功
            try:
                # 以下except都是用来捕获当requests请求出现异常时，
                # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
                requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
                res = requests.post("http://w.eydata.net/521270375f95bba8", payload, verify=False)
                res.raise_for_status()
                # res = requests.get(w_url, headers=__headers_mobile, verify=False)
                # res.raise_for_status()
                break
            except requests.exceptions.HTTPError:
                text.insert(END, "HTTPError, 等待5秒后重新尝试登录!!!")
                text.update()
                text.see(END)
                time.sleep(5)
            except requests.exceptions.ConnectionError:
                text.insert(END, "ConnectionError, 等待5秒后重新尝试登录!!!")
                text.update()
                text.see(END)
                time.sleep(5)
            except requests.exceptions.ChunkedEncodingError:
                text.insert(END, "ChunkedEncodingError, 等待5秒后重新尝试登录!!!")
                text.update()
                text.see(END)
                time.sleep(5)
            except:
                text.insert(END, "Unfortunitely -- An Unknow Error Happened, 等待5秒后重新尝试登录!!!")
                text.update()
                text.see(END)
                time.sleep(5)
        if len(res.text) == 32:
            text.insert(END, "登录成功!!!")
            text.update()
            text.see(END)
            QJ.zhuangtaima = res.text
            config = configparser.ConfigParser()
            config.read('.\\config.ini')
            if config.has_section('基本设置') == False:
                config.add_section('基本设置')

            config.set('基本设置', '单卡卡密', str(QJ.dkkm))
            config.set('基本设置', '状态码', str(QJ.zhuangtaima))

            o = open('.\\config.ini', 'w')
            config.write(o)
            o.close()  # 不要忘记关闭
            if var2.get() == 1:
                __openchrome()
            # master.destroy()
            # root.wm_attributes("-topmost", 1)
            # time.sleep(1)
            # root.wm_attributes("-topmost", 0)
        else:
            if var6.get() != 1:
                text.insert(END, "登录失败!!!错误代码:" + res.text)
                text.update()
                text.see(END)
            else:
                while len(res.text) != 32:
                    QJ.dkkm = dkkmbjk.get()
                    QJ.jiqima = jiqimabjk.get()
                    #print(QJ.dkkm)
                    #print(QJ.jiqima)
                    payload = {"SingleCode": QJ.dkkm,
                               "Ver": "1.0",
                               "Mac": QJ.jiqima}
                    #res = requests.post("http://w.eydata.net/521270375f95bba8", payload)
                    while True:  # 一直循环，知道访问站点成功
                        try:
                            # 以下except都是用来捕获当requests请求出现异常时，
                            # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
                            requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
                            res = requests.post("http://w.eydata.net/521270375f95bba8", payload, verify=False)
                            res.raise_for_status()
                            # res = requests.get(w_url, headers=__headers_mobile, verify=False)
                            # res.raise_for_status()
                            break
                        except requests.exceptions.HTTPError:
                            text.insert(END, "HTTPError, 等待5秒后重新尝试登录!!!")
                            text.update()
                            text.see(END)
                            time.sleep(5)
                        except requests.exceptions.ConnectionError:
                            text.insert(END, "ConnectionError, 等待5秒后重新尝试登录!!!")
                            text.update()
                            text.see(END)
                            time.sleep(5)
                        except requests.exceptions.ChunkedEncodingError:
                            text.insert(END, "ChunkedEncodingError, 等待5秒后重新尝试登录!!!")
                            text.update()
                            text.see(END)
                            time.sleep(5)
                        except:
                            text.insert(END, "Unfortunitely -- An Unknow Error Happened, 等待5秒后重新尝试登录!!!")
                            text.update()
                            text.see(END)
                            time.sleep(5)
                    if len(res.text) == 32:
                        text.insert(END, "登录成功!!!")
                        text.update()
                        text.see(END)
                        QJ.zhuangtaima = res.text
                        config = configparser.ConfigParser()
                        config.read('.\\config.ini')
                        if config.has_section('基本设置') == False:
                            config.add_section('基本设置')

                        config.set('基本设置', '单卡卡密', dkkmbjk.get())

                        o = open('.\\config.ini', 'w')
                        config.write(o)
                        o.close()  # 不要忘记关闭
                        # master.destroy()
                        # root.wm_attributes("-topmost", 1)
                        # time.sleep(1)
                        # root.wm_attributes("-topmost", 0)
                    else:
                        text.insert(END, "登录失败,5秒后重试!!!错误代码:" + res.text)
                        text.update()
                        text.see(END)
                        time.sleep(5)
    else:
        tkinter.messagebox.showinfo('提示', '请输入单卡卡密!!!')







def jiqimazhuanbang():
    QJ.dkkm = dkkmbjk.get()
    QJ.jiqima = jiqimabjk.get()
    #print(QJ.dkkm)
    #print(QJ.jiqima)
    payload = {"UserName": QJ.dkkm,
               "UserPwd": "",
               "Mac": QJ.jiqima,
               "Type":""}

    #res = requests.post("http://w.eydata.net/32481283946216a7",payload)
    while True:  # 一直循环，知道访问站点成功
        try:
            # 以下except都是用来捕获当requests请求出现异常时，
            # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
            requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
            res = requests.post("http://w.eydata.net/32481283946216a7", payload, verify=False)
            res.raise_for_status()
            # res = requests.get(w_url, headers=__headers_mobile, verify=False)
            # res.raise_for_status()
            break
        except requests.exceptions.HTTPError:
            text.insert(END, "HTTPError, 等待5秒后重新尝试登录!!!")
            text.update()
            text.see(END)
            time.sleep(5)
        except requests.exceptions.ConnectionError:
            text.insert(END, "ConnectionError, 等待5秒后重新尝试登录!!!")
            text.update()
            text.see(END)
            time.sleep(5)
        except requests.exceptions.ChunkedEncodingError:
            text.insert(END, "ChunkedEncodingError, 等待5秒后重新尝试登录!!!")
            text.update()
            text.see(END)
            time.sleep(5)
        except:
            text.insert(END, "Unfortunitely -- An Unknow Error Happened, 等待5秒后重新尝试登录!!!")
            text.update()
            text.see(END)
            time.sleep(5)
    if res.text == "1":
        text.insert(END, "机器码换绑成功!!!")
        text.update()
        text.see(END)
    else:
        text.insert(END, "机器码换绑失败!!!错误代码:" + res.text)
        text.update()
        text.see(END)

def ipmazhuanbang():
    QJ.dkkm = dkkmbjk.get()
    QJ.jiqima = jiqimabjk.get()
    #print(QJ.dkkm)
    #print(QJ.jiqima)
    payload = {"SingleCode": QJ.dkkm}

    # res = requests.post("http://w.eydata.net/32481283946216a7",payload)
    while True:  # 一直循环，知道访问站点成功
        try:
            # 以下except都是用来捕获当requests请求出现异常时，
            # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
            requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
            res = requests.post("http://w.eydata.net/51f0cf1ffba45b7d", payload, verify=False)
            res.raise_for_status()
            # res = requests.get(w_url, headers=__headers_mobile, verify=False)
            # res.raise_for_status()
            break
        except requests.exceptions.HTTPError:
            text.insert(END, "HTTPError, 等待5秒后重新尝试登录!!!")
            text.update()
            text.see(END)
            time.sleep(5)
        except requests.exceptions.ConnectionError:
            text.insert(END, "ConnectionError, 等待5秒后重新尝试登录!!!")
            text.update()
            text.see(END)
            time.sleep(5)
        except requests.exceptions.ChunkedEncodingError:
            text.insert(END, "ChunkedEncodingError, 等待5秒后重新尝试登录!!!")
            text.update()
            text.see(END)
            time.sleep(5)
        except:
            text.insert(END, "Unfortunitely -- An Unknow Error Happened, 等待5秒后重新尝试登录!!!")
            text.update()
            text.see(END)
            time.sleep(5)
    if res.text == "1":
        text.insert(END, "ip换绑成功!!!")
        text.update()
        text.see(END)
    else:
        text.insert(END, "ip换绑失败!!!错误代码:" + res.text)
        text.update()
        text.see(END)

def loginout():
    QJ.dkkm = dkkmbjk.get()
    payload = {"StatusCode": QJ.zhuangtaima,
               "UserName": QJ.dkkm}
    res = requests.post("http://w.eydata.net/129cbfe8e3694512",payload)
    if res.text == "1":
        text.insert(END, "成功退出登录!!!")
        text.update()
        text.see(END)

def loginout2():
    QJ.dkkm = dkkmbjk.get()
    config = configparser.ConfigParser()
    config.read('.\\config.ini')
    config.items('基本设置')
    tuichu_zhuangtaima = config.get('基本设置', '状态码')
    if tuichu_zhuangtaima == "":
        tkinter.messagebox.showinfo('提示', '你还没有登录!!!')
    else:
        payload = {"StatusCode": tuichu_zhuangtaima,
                   "UserName": QJ.dkkm}
        res = requests.post("http://w.eydata.net/129cbfe8e3694512", payload)
    if res.text == "1":
        text.insert(END, "成功退出登录!!!")
        text.update()
        text.see(END)
        time.sleep(5)

def on_closing():
    if messagebox.askokcancel("提示", "是否要退出软件?"):
        if QJ.zhuangtaima != "":
            loginout()
            root.quit()
        else:
            root.quit()

#识别分割线----------------------------------------------------------------------------------
def Euclidean_distance(a, b):#欧氏距离
    return sum((np.array(a)-np.array(b))**2)**(0.5)
def clustering(temp_get):#用DBSCAN聚类
    mod = sklearn.cluster.DBSCAN(eps=5,min_samples=8,)
    mod.fit(temp_get)
    pro = mod.fit_predict(temp_get)
    pro = np.array(pro)
    index, num = np.unique(pro,return_counts=True)
    max_num =index[np.where(np.array(num)==np.array(num).max())]
    temp_get = [temp_get[i] for i in range(len(temp_get)) if pro[i] == max_num]
    return temp_get

def image_pyramid():#预处理，图像金字塔
    image_find =cv2.imread("1.png")
    image_big = cv2.imread("2.png")
    for i in range(6):
        image_find = cv2.pyrDown(image_find)
        #cv2.imshow('1',image_find)
        #print(image_find.shape)
    cv2.imwrite('1_temp.png', image_find)
    for i in range(3):
        image_big = cv2.pyrDown(image_big)
        #cv2.imshow('1',image_big)
        #print(image_find.shape)
    cv2.imwrite('2_temp.png', image_big)
def image_contrast():#再次读取图片进行操作
    image_find = Image.open("1_temp.png")
    image_big = Image.open("2_temp.png")
    data1 = image_find.load()
    data2 = image_big.load()
    x,y = image_big.size
    a = list(data1[0,0])
    temp_get=[]
    for i in range(x):
        for j in range(y):
            b= data2[i,j]
            temp = Euclidean_distance(a,b)#统计整张图片的的像素点与目标图像像素点的欧氏距离
            if temp < 50:
                temp_get.append([i,j])#保存符合要求的像素点的位置
    temp_get = clustering(temp_get)#聚类，返回最大的那一类的坐标
    data2 = Draw_square(temp_get,data2)
    #image_big.show()


def Draw_square(temp_get, data2):#画图，画出正方形框起来
    temp_x = [temp_get[i][0] for  i in range(len(temp_get))]
    temp_y = [temp_get[i][1] for  i in range(len(temp_get))]
    temp_y = np.array(temp_y)
    temp_x = np.array(temp_x)
    max_x = int(temp_x.max())
    max_y = int(temp_y.max())
    min_x = int(temp_x.min())
    min_y = int(temp_y.min())
    QJ.max_x = max_x
    # for i in range(max_x-min_x):
    #     data2[min_x+i, min_y] = (255, 0, 0)
    #     data2[min_x+i, max_y] = (255, 0, 0)
    # for j in range(max_y-min_y):
    #     data2[min_x, min_y+j] = (255, 0, 0)
    #     data2[max_x, min_y+j] = (255, 0, 0)
    # return data2

#拖动滑块分割线------------------------------------
def get_track(distance):      # distance为传入的总距离
    # 移动轨迹
    track=[]
    # 当前位移
    current=0
    # 减速阈值
    mid=distance*4/5
    # 计算间隔
    t=0.2
    # 初速度
    v=1

    while current<distance:
        if current<mid:
            # 加速度为2
            a=4
        else:
            # 加速度为-2
            a=-3
        v0=v
        # 当前速度
        v=v0+a*t
        # 移动距离
        move=v0*t+1/2*a*t*t
        # 当前位移
        current+=move
        # 加入轨迹
        track.append(round(move))
    return track
# def move_to_gap(slider,tracks):     # slider是要移动的滑块,tracks是要传入的移动轨迹
#     ActionChains(driver).click_and_hold(slider).perform()
#     for x in tracks:
#         ActionChains(driver).move_by_offset(xoffset=x,yoffset=0).perform()
#     time.sleep(0.5)
#     ActionChains(driver).release().perform()

root = Tk()   #生成一个主窗口对象
root.title('奥利给丶快手批量下载助手V2.20 正式版') #标题
width = 579
height = 822
screenwidth = root.winfo_screenwidth()
screenheight = root.winfo_screenheight()
alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth-width)/2, (screenheight-height)/2)
root.geometry(alignstr)
root.resizable(width=False, height=True)
#root.geometry('672x822+600+100') #大小位置
root.protocol('WM_DELETE_WINDOW', on_closing)
#webbrowser.open_new_tab("http://zanzhu.xiaobb.club/")

if not os.path.exists('.\\config.ini'):
    open('.\\config.ini', "w")
if not os.path.getsize('.\\config.ini'):
    config = configparser.ConfigParser()
    config.read('.\\config.ini')
    if config.has_section('基本设置') == False:
        config.add_section('基本设置')
        config.set('基本设置', '自动模式', "0")
        config.set('基本设置', '免登录', "0")
        config.set('基本设置', '延时', "1")
        config.set('基本设置', '已存在次数', "20")
        config.set('基本设置', '自动跳过', "0")
        config.set('基本设置', '验证码出现次数', "20")
        config.set('基本设置', '浏览器最大化', "0")
        config.set('基本设置', '使用QQ登录', "0")
        config.set('基本设置', '只下载视频', "0")
        config.set('基本设置', '只下载图集', "0")
        config.set('基本设置', '老版本参数', "0")
        config.set('基本设置', '参数版本自动判断', "0")
        config.set('基本设置', '没有作品重启计次', "0")
        config.set('基本设置', '分享的短链', '')

    if config.has_section('cookie') == False:
        config.add_section('cookie')
        config.set('cookie', 'did', "")
        config.set('cookie', 'kuaishou.live.web_st', "")
        config.set('cookie', 'kuaishou.live.web_ph', "")
        config.set('cookie', 'kuaishou.live.bfb1s', "")
        config.set('cookie', 'userId', "")

    if config.has_section('用户日志') == False:
        config.add_section('用户日志')
        config.set('用户日志', '当前uid', "0")
        config.set('用户日志', '当前解析视频数', "0")

    o = open('.\\config.ini', 'w')
    config.write(o)
    o.close()  # 不要忘记关闭

#-------------------------------------分割线

config = configparser.ConfigParser()
config.read('.\\config.ini')

__read_preset()

# print('sections:', ' ', config.sections())
#
# # -options(section)得到该section的所有option
# print('options:', ' ', config.options('config'))
#
# # -items（section）得到该section的所有键值对
# print('items:', ' ', config.items('cmd'))
#
# # -get(section,option)得到section中option的值，返回为string类型
# print('get:', ' ', config.get('cmd', 'startserver'))
#
# # -getint(section,option)得到section中的option的值，返回为int类型
# print('getint:', ' ', config.getint('cmd', 'id'))
# print('getfloat:', ' ', config.getfloat('cmd', 'weight'))
# print('getboolean:', '  ', config.getboolean('cmd', 'isChoice'))
# """
# 首先得到配置文件的所有分组，然后根据分组逐一展示所有
# """
#
# for sections in config.sections():
#     for items in config.items(sections):
#         print(items)

config.items('cookie')
QJ.cookie1 = config.get('cookie', 'did')
QJ.cookie2 = config.get('cookie', 'kuaishou.live.web_st')
QJ.cookie3 = config.get('cookie', 'kuaishou.live.web_ph')
QJ.cookie4 = config.get('cookie', 'kuaishou.live.bfb1s')
QJ.cookie5 = config.get('cookie', 'userId')


text = Listbox(root,width=82,height=30)
text.grid(row=0,columnspan=3, sticky=W)

# button=Button(root,text="1.初始",width=10,command=lambda :thread_it(__init__, ))
# button.grid(row=5,column=0,sticky=W)

duanlian_list = config.get('基本设置', '分享的短链')
QJ.duanlian_list = duanlian_list.split('丨')

# jiqimabq = Label(root, text='机器码:')
# jiqimabq.place(x=15,y=545)
#
# jiqimabjk = Entry(root, width=40)
# jiqimabjk.place(x=60,y=545)
# jiqimabjk.insert(0, config.get('基本设置', '机器码'))
# jiqima = config.get('基本设置', '机器码')
# QJ.jiqima = jiqima
#
# dkkmbq = Label(root, text='单卡卡密:')
# dkkmbq.place(x=2,y=575)
#
# dkkmbjk = Entry(root, width=40)
# dkkmbjk.place(x=60,y=575)
# dkkm = config.get('基本设置', '单卡卡密')
# if dkkm != "":
#     dkkmbjk.insert(0, config.get('基本设置', '单卡卡密'))
#     QJ.dkkm = dkkmbjk.get()
#
#
# dkkmban = Button(root, text="登录", width=8, command=lambda :thread_it(login, ))  # ,command=lambda :thread_it(one_click_access, )
# dkkmban.place(x=350,y=545)
#
# dkkman2 = Button(root, text="机器码转绑", width=8, command=lambda :thread_it(jiqimazhuanbang, ))  # ,command=lambda :thread_it(one_click_access, )
# dkkman2.place(x=430,y=545)
#
# dkkmban3 = Button(root, text="ip转绑", width=8, command=lambda :thread_it(ipmazhuanbang, ))  # ,command=lambda :thread_it(one_click_access, )
# dkkmban3.place(x=510,y=545)
#
# dkkmban4 = Button(root, text="退出登录", width=10, command=lambda :thread_it(loginout2, ))  # ,command=lambda :thread_it(one_click_access, )
# dkkmban4.place(x=370,y=745)

var2 = IntVar()
Checkbutton2 = Checkbutton(root,text="自动模式",  variable=var2)
Checkbutton2.place(x=15,y=615)
if config.getint('基本设置', '自动模式') == 1:
    Checkbutton2.select()
    thread_it(__init__, )

var8 = IntVar()
Checkbutton8 = Checkbutton(root,text="免登陆",  variable=var8)
Checkbutton8.place(x=15,y=645)
if config.getint('基本设置', '免登录') == 1:
    Checkbutton8.select()


var4 = IntVar()
Checkbutton4 = Checkbutton(root,text="浏览器最大化",  variable=var4)
Checkbutton4.place(x=15,y=705)
if config.getint('基本设置', '浏览器最大化') == 1:
    Checkbutton4.select()

var5 = IntVar()
Checkbutton5 = Checkbutton(root,text="使用QQ登录",  variable=var5)
Checkbutton5.place(x=15,y=675)
if config.getint('基本设置', '使用QQ登录') == 1:
    Checkbutton5.select()

var7 = IntVar()
Checkbutton7 = Checkbutton(root,text="只下载视频",  variable=var7)
Checkbutton7.place(x=150,y=645)
if config.getint('基本设置', '只下载视频') == 1:
    Checkbutton7.select()

var3 = IntVar()
Checkbutton3 = Checkbutton(root,text="只下载图集",  variable=var3)
Checkbutton3.place(x=150,y=675)
if config.getint('基本设置', '只下载图集') == 1:
    Checkbutton3.select()

var9 = IntVar()
Checkbutton9 = Checkbutton(root,text="老版本参数(最多500个)",  variable=var9)
Checkbutton9.place(x=15,y=735)
if config.getint('基本设置', '老版本参数') == 1:
    Checkbutton9.select()

var10 = IntVar()
Checkbutton10 = Checkbutton(root,text="参数版本自动判断",  variable=var10)
Checkbutton10.place(x=15,y=765)
if config.getint('基本设置', '参数版本自动判断') == 1:
    Checkbutton10.select()

# var6 = IntVar()
# Checkbutton6 = Checkbutton(root,text="单卡卡密自动登录",  variable=var6)
# Checkbutton6.place(x=350,y=575)
# if config.getint('基本设置', '单卡卡密自动登录') == 1:
#     Checkbutton6.select()
#     thread_it(login, )

button8=Button(root,text="清除cookie并重启",width=15,command=lambda :thread_it(qccookie, ))
button8.place(x=335,y=545)

button5=Button(root,text="保存配置",width=10,command=lambda :thread_it(save_config_jb, ))
button5.place(x=480,y=545)

button6=Button(root,text="视频从新开始",width=10,command=lambda :thread_it(save_config_jb4, ))
button6.place(x=135,y=545)

button7=Button(root,text="全部重新开始",width=10,command=lambda :thread_it(save_config_jb3, ))
button7.place(x=235,y=545)

label = Label(root,text='延时时间:')
label.place(x=280,y=647)

entry = Entry(root,width=10)
entry.place(x=340,y=647)
entry.insert(0,config.get('基本设置', '延时'))

yichuxiancishu = Label(root, text='已出现次数')
yichuxiancishu.place(x=100,y=615)

label2 = Label(root,text='出现次数:')
label2.place(x=280,y=677)

entry2 = Entry(root,width=10)
entry2.place(x=340,y=677)
entry2.insert(0,config.get('基本设置', '已存在次数'))


label3 = Label(root,text='没有作品重启时间:')
label3.place(x=230,y=707)

entry3 = Entry(root,width=10)
entry3.place(x=340,y=707)
entry3.insert(0,config.get('基本设置', '没有作品重启时间'))

label4 = Label(root,text='没有作品最大次数:')
label4.place(x=230,y=737)

entry4 = Entry(root,width=10)
entry4.place(x=340,y=737)
entry4.insert(0,config.get('基本设置', '没有作品最大次数'))

var = IntVar()
Checkbutton = Checkbutton(root,text="自动跳过当前",  variable=var)
Checkbutton.place(x=450,y=675)
if config.getint('基本设置', '自动跳过') == 1:
    Checkbutton.select()

QJ.yzm_num = int(config.get('基本设置', '验证码出现次数'))
#读取用户log配置保存到class全局变量
QJ.current_uid = config.get('用户日志', '当前uid')
QJ.video_num = int(config.get('用户日志', '当前解析视频数'))

button4=Button(root,text="一键跳过当前",width=10,command=lambda :thread_it(stop, ))
button4.place(x=455,y=645)

button1=Button(root,text="一键获取uid",width=10,command=lambda :thread_it(one_click_access, ))
button1.place(x=20,y=545)

button1=Button(root,text="开始",width=10,command=lambda :thread_it(__init__, ))
button1.place(x=20,y=585)

button2=Button(root,text="退出",width=10,command=on_closing)
button2.place(x=480,y=585)


# master = tkinter.Toplevel()  # 生成一个主窗口对象
# #master.attributes("-toolwindow", 1)
# master.wm_attributes("-topmost", 1)
# master.title('奥利给丶快手批量下载助手登录窗口')  # 标题
# master.geometry('416x109+700+300')  # 大小位置
#
# jiqimabq = Label(master, text='机器码:')
# jiqimabq.grid(row=0, sticky=W)
#
# jiqimabjk = Entry(master, width=40)
# jiqimabjk.grid(row=0, column=1, sticky=W)
# jiqimabjk.insert(0, config.get('基本设置', '机器码'))
#
# dkkmbq = Label(master, text='单卡卡密:')
# dkkmbq.grid(row=1, sticky=W)
#
# dkkmbjk = Entry(master, width=40)
# dkkmbjk.grid(row=1, column=1, sticky=W)
# dkkm = config.get('基本设置', '机器码')
# if dkkm != "":
#     dkkmbjk.insert(0, config.get('基本设置', '单卡卡密'))
#
# dkkmban = Button(master, text="登录", width=8, command=lambda :thread_it(login, ))  # ,command=lambda :thread_it(one_click_access, )
# dkkmban.grid(row=3, column=0, sticky=W)
#
# dkkman2 = Button(master, text="机器码转绑", width=8)  # ,command=lambda :thread_it(one_click_access, )
# dkkman2.grid(row=3, column=1)
#
# dkkmban3 = Button(master, text="ip转绑", width=8)  # ,command=lambda :thread_it(one_click_access, )
# dkkmban3.grid(row=3, column=2, sticky=E)

root.mainloop()